Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to make a class in python

class Person:
  def __init__(self, _name, _age):
    self.name = _name
    self.age = _age
   
  def sayHi(self):
    print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
    
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
Comment

create and use python classes

class Mammal:
    def __init__(self, name):
        self.name = name

    def walk(self):
        print(self.name + " is going for a walk")


class Dog(Mammal):
    def bark(self):
        print("bark!")


class Cat(Mammal):
    def meow(self):
        print("meow!")


dog1 = Dog("Spot")
dog1.walk()
dog1.bark()
cat1 = Cat("Juniper")
cat1.walk()
cat1.meow()
Comment

how to declare a class in python

class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
  	def __init__(self, var1=0, var2):
    
    	#the name of the construct must be "__init__" or it won't work
    	#the arguments "self" is mandatory but you can add more if you want 
    	self.age = var1
    	self.name = var2
    
    	#the construct will be execute when you declare an instance of this class
    
  	def otherFunction(self):
    	
        #the other one work like any basic fonction but in every methods,
    	#the first argument (here "self") return to the class in which you are
 	
Comment

classes in python

# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A

class Fan:

    def __init__(self, company, color, number_of_wings):
        self.company = company
        self.color = color
        self.number_of_wings = number_of_wings
        
    def PrintDetails(self):
        print('This is the brand of',self.company,'its color is', self.color,' and it has',self.number_of_wings,'petals')
    
        
    def switch_on(self):
        print("fan started")
        
    def switch_off(self):
        print("fan stopped")
        
    def speed_up(self):
        print("speed increased by 1 unit")
        
    def speed_down(self):
        print("speed decreased by 1 unit")
        
usha_fan = Fan('usha','skin',5)
fan = Fan('bajaj','wite', 4)


print('these are the details of this fan')
usha_fan.PrintDetails()
print()

usha_fan.switch_on()
Comment

what is a class in python

A class is a block of code that holds various functions. Because they
are located inside a class they are named methods but mean the samne
thing. In addition variables that are stored inside a class are named 
attributes. The point of a class is to call the class later allowing you 
to access as many functions or (methods) as you would like with the same
class name. These methods are grouped together under one class name due
to them working in association with eachother in some way.
Comment

how to define a class in python

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

    def say_name(self):
      print(f"Hello, I am {self.name}")

p1 = Person("Sara", 18)
p1.say_name() 
Comment

creating class and object in python

class Parrot:

    # class attribute
    species = "bird"

    # instance attribute
    def __init__(self, name, age):
        self.name = name
        self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
Comment

Creating Class and Object in Python

class Parrot:
    # class attribute
    species = "bird"
    # instance attribute
    def __init__(self, name, age):
        self.name = name
        self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
Comment

Class in python

# Node class
class Node:
  
    # Function to initialize the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize
                          # next as null
  
# Linked List class
class LinkedList:
    
    # Function to initialize the Linked
    # List object
    def __init__(self):
        self.head = None
Comment

classes in python

class Foo:
  def __init__(self):
    self.definition = Foo!
  def hi():
    # Some other code here :)
    
# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
      
Comment

objects and classes in python

class IntellipaatClass:
	a = 5
	def function1(self):
		print(‘Welcome to Intellipaat’)
#accessing attributes using the class object of same name
IntellipaatClass.function(1)
print(IntellipaatClass.a)
Comment

what is an object in python

#objects are collections of data
Comment

class in python

class LuckyLemur():
  	def __init__(self, description):
		self.description = description
	
    def reveal_description(self):
    	print(f'Lucky Lemur is {self.description}')

lucky_lemur = LuckyLemur('Pro')
lucky_lemur.reveal_description()
Comment

creating python classes

class car:
  def __init__(self, model, color):
    self.model = model
    self.color = color
         
tesla = car("model 3", "black")
Comment

how to use a class in python

class awwab(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def speak(self):
        print("Hello, my name is",self.name,"and I am",self.age,"years old!")
        
awwabasad = awwab("Awwab Asad", 11)
print(awwabasad.speak())
Comment

Python classes and objects

class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def greet(self, person_to_greet):
        # person_to_greet will be another Person object
        print(f"Hey {person_to_greet.name}, nice to meet you I'm {self.name}")

    def ask_age(self, ask_from):
        print(f"{self.name}: {ask_from.name}, How old are you?")
        print(f"{ask_from.name}: i am {ask_from.age}")


# Creating a person object
tom = Person("Tom", 50, "Male")

# we can also create an object with keyword arguments
jack = Person(name="Jack", age=19, gender="Male")

# Here we call the greet method of tom, and we pass the Jack Person Object Created above
tom.greet(jack)

# if we call the greet method of jack and pass the Tom person object, then jack greets tom
jack.greet(tom)

# Here Jack will ask age of tom, and tom will reply with his age
jack.ask_age(tom)
Comment

Python Class Example

#Source: https://vegibit.com/python-class-examples/
class Vehicle:
    def __init__(self, brand, model, type):
        self.brand = brand
        self.model = model
        self.type = type
        self.gas_tank_size = 14
        self.fuel_level = 0

    def fuel_up(self):
        self.fuel_level = self.gas_tank_size
        print('Gas tank is now full.')

    def drive(self):
        print(f'The {self.model} is now driving.')

obj = Vehicle("Toyota", "Carola", "Car")
obj.drive()
Comment

Python class example

class Greet:
	def __init__(self, names):
    	self.names = names

	def say_hello(self):
    	for name in self.names:
        	print("Hello " + name)
Comment

simple python class

class Person:
    def say_hi(self):
        print('Hello, how are you?')

p = Person()
p.say_hi()
# The previous 2 lines can also be written as
# Person().say_hi()
Comment

python how to create a class

class class_name:
	def __init__(self):
    	# class variables(can be used all over the class)
        pass
first_class = class_name() # creating the class
Comment

classes in python

>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>
Comment

what is a class in python

# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A

Classes are blueprint used to construct objects
Comment

can you make a class in a class python

# Yes 
class Main:
  # outer class
  class Inner():
    # inner class
    pass
Comment

Defining a Class in Python

class MyNewClass:
    '''This is a docstring. I have created a new class'''
    pass
Comment

python classes and objects

class employee:
    name = ''
    id = 0
    department = ''

    def pay(self):
        print(self.name, self.id, self.department)


s = employee()
s.name = 'burhan'
s.id = 0o2234523
s.department = 'Development'
s.pay()

b = employee()
b.name = 'Abdullah'
b.id =12423432857
b.department = 'Software Engineer'
b.pay()

c = employee()
c.name = 'Bilal'
c.id =12423432857
c.department = 'Software Engineer'
c.pay()
Comment

classes in python

fromr random import radint

Asnwer= randint(1,200)
count= 0

while true:
  guess  = getingeger("whatis yourestimate")
  if guess< 1 or guess > 200:
    print(your estimate must be between 1 and 200)
    
    continue
    
  count+ = 1
  if guess < answer:
    print("higher")
  elif guess > answer:
    print("lower")
  else:
    print("you guessed it!")
    
if count== 1
	print("wow first try!!")

  else:
    print("you estimated it in, count,'time'")
Comment

class python example

def ok(index):
    print(index) > Hi!
ok("Hi!")
class Lib:
    def ok(self,Token):
        print(Token) > Hello World!
Library = Lib()
Library.ok("Hello World!")
Comment

classes in python

class fruit:
  def __init__(self,color,taste,name):
    self.color = color
    self.name = name
    self.taste = taste
    
    def myfunc(self):
      print("{} = Taste:{}, Color:{}".format(self.name, self.taste, self.color))
      
f1 = fruit("Red", "Sweet", "Red Apple")
f1.myfunc()
Comment

python object creation

def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))
Comment

Creating an Object in Python

>>> harry = Person()
Comment

python class declaration

#Testing
class Class_Def:
  def __init__(self):
    pass
Comment

PREVIOUS NEXT
Code Example
Python :: pandas add prefix zeros to column values 
Python :: what is django 
Python :: check django version windows 
Python :: enumerate in range python 
Python :: python count 
Python :: how to pick everything after a character in python 
Python :: python tkinter ttk 
Python :: skimage local threshold 
Python :: how to get mac in python 
Python :: python scipy moving average 
Python :: flatmap in python 
Python :: print example in python 
Python :: matplotlib savefig cutting off graph 
Python :: subset in python 
Python :: Change Python interpreter in pycharm 
Python :: how to use def in python 
Python :: Jinja for items in list 
Python :: list pop python 
Python :: python singleton 
Python :: python set match two list 
Python :: tkinter filedialog how to show more than one filetype 
Python :: python generic 
Python :: datetime column only extract date pandas 
Python :: concatenation array 
Python :: generate n different colors matplotlib 
Python :: python generate html 
Python :: .format python 3 
Python :: python how to insert values into string 
Python :: python multithreading 
Python :: install scrapy on pycharm 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =