python中的类
1、Like the means it seems.the meaning of class is create object instantiation.
For instance
classDog:"""a simple attempt to simulate a puppy""" def __init__(self, name, age):"""initialize properties name and age"""self.name=name
self.age=agedefsit(self):"""simulate dog sit when commanded""" print(f"{self.name}is now sitting.")defroll_over(self):"""simulate dog roll over when commanded""" print(f"{self.name}roll over!")
my_dog=Dog('Henry',6) #create one class and initialize it print(f"my dog's name is {my_dog.name}")
my_dog.sit()#call method
2、then ,we maybe want to know,if we need revise the value of attributes,what we need to do ?
we can revise it straightly
my_dog.age=12
print
(f
"
my dog's age is {my_dog.age}
"
)
or we can revise it by method
defupdate_age(self,dog_age):
self.age=dog_ageprint(f"{self.name}is {self.age}.")#revise the value of age
3、inherit
someone may want to know why we need inherit.sometimes,we have several function need to created but the functionality is the same,so we can inhreit another class to derease our repeated code.the class be called is father,the other is subclass.
class Car:#subclass must behind the father,and father must in included in file def __init__(self, make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0defget_discriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}" returnlong_name.title()defread_odometer(self):print(f"this car has {self.odoment_reading}miles on it")defupdate_odometer(self,mileage):if mileage>=self.odometer_reading:
self.odometer_reading=mileageelse:print("You can't roll back an odometer")defincrement_odometer(self,miles):
self.odometer_reading+=milesclass ElectricCar(Car): #subclass is defined,and father'name must be appointed in parentheses def __init__(self, make, model, year):
super().__init__(make, model, year)#call father's method self.battery_size=75 defdescribe_battery(self):print(f"This car has a {self.battery_size}-kwh battery.")
my_tesla=ElectricCar('tesla','model s',2019)print(my_tesla.get_discriptive_name())
my_tesla.describe_battery()
then ,we need to consider one problem that if we need create one class which has been writed already,we do not want to write it again.we maybe recall the same solvement used in function.we can do it like do in function.import the class from module
from Class_2 importCar
my_new_car=Car('audi','a4',2016)print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading=23my_new_car.read_odometer()
thank you for your reading.