9. Class
9.1 Creating and using classes
class Dog():
#Similar to initialization of c++ data
def __init__(self,name,age):
self.name = name
self.age = age
#class function
def sit(self):
print(" The name of the puppy is: "+" "+self.name)
print(" The age of the puppy is: "+" "+str(self.age))
self is equivalent to this pointer
9.2 Create a sample instance (object)
first_dog = Dog(' Wangwang ',6)
print(first_dog.name)
print(first_dog.age)
first_dog.sit()
9.3 Working with classes and instances (objects)
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def get(self):
long_name = str(self.year)+''+self.make+''+self.model
return long_name
my_car = Car('s','d',5)
print(my_car.get())
9.3.1 Assigning default values to properties
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.title = 0
def get(self):
long_name = str(self.year)+''+self.make+''+self.model
return long_name
my_car = Car('s','d',5)
print(my_car.get())
print(my_car.title)
9.4 Inheritance
When a class inherits another class, it will automatically get all the properties and methods of the other class; the original class is called the parent class, and the parent class is called the child class.
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.title = 0
def get(self):
long_name = str(self.year)+''+self.make+''+self.model
return long_name
class ElectricCar(Car):
#super() inherits the properties of the parent class and calls it.
def __init__(self,make,model,year):
super().__init__(make,model,year)
my_ElectricCar = ElectricCar('s','d','f')
print(my_ElectricCar.make)