classCar: wheels =0def__init__(self,color,model,year): self.color = color self.model = model self.year = year
这样的话,我们在调用wheels这个变量时,可以通过实例,或者直接调用Car.wheels:
my_car =Car("yellow", "beetle", 1967)print(f"My car is {my_car.color}")print(f"It has {Car.wheels} wheels")print(f"It has {my_car.wheels} wheels")Out:My car is yellowIt has 0 wheelsIt has 0 wheels
my_car =Car("yellow", "Beetle", "1966")my_other_car =Car("red", "corvette", "1999")print(f"My car is {my_car.color}")print(f"It has {my_car.wheels} wheels")print(f"My other car is {my_other_car.color}")print(f"It has {my_other_car.wheels} wheels")Out:My car is yellowIt has 0 wheelsMy other car is redIt has 0 wheels
# Change the class variable valueCar.wheels =4print(f"My car has {my_car.wheels} wheels")print(f"My other car has {my_other_car.wheels} wheels")Out:My car has 4 wheelsMy other car has 4 wheels
# Change the instance variable value for my_carmy_car.wheels =5print(f"My car has {my_car.wheels} wheels")print(f"My other car has {my_other_car.wheels} wheels")Out:My car has 5 wheelsMy other car has 4 wheels
classCar: wheels =0def__init__(self,color,model,year): self.color = color self.model = model self.year = year self._cupholders =6my_car =Car("yellow", "Beetle", "1969")print(f"It was built in {my_car.year}")Out:It was built in1969
my_car =Car("yellow", "Beetle", "1969")print(f"It was built in {my_car.year}")print(f"It has {my_car.__cupholders} cupholders.")Out:It was built in1969---------------------------------------------------------------------------AttributeErrorTraceback (most recent call last)<ipython-input-108-1efe56f0c054>in<module>1 my_car =Car("yellow", "Beetle", "1969")2print(f"It was built in {my_car.year}")---->3print(f"It has {my_car.__cupholders} cupholders.")AttributeError:'Car'object has no attribute '__cupholders'
my_car =Car("yellow", "beetle", 1969)print(f"My car was built in {my_car.year}")my_car.year =2003print(f"It was built in {my_car.year}")del my_car.yearprint(f"It was built in {my_car.year}")Out:My car was built in1969It was built in2003---------------------------------------------------------------------------AttributeErrorTraceback (most recent call last)<ipython-input-110-46914b0bae82>in<module>67del my_car.year---->8print(f"It was built in {my_car.year}")AttributeError:'Car'object has no attribute 'year'
classCar:def__init__(self,color,model,year): self.color = color self.model = model self.year = year self._voltage =12@propertydefvoltage(self):return self._voltage@voltage.setterdefvoltage(self,volts):print("Warning: this can cause problems!") self._voltage = volts@voltage.deleterdefvoltage(self):print("Warning: the radio will stop working!")del self._voltage
my_car =Car("yellow", "beetle", 1969)print(f"My car uses {my_car.voltage} volts")my_car.voltage =6print(f"My car now uses {my_car.voltage} volts")del my_car.voltageOut:My car uses 12 voltsWarning: this can cause problems!My car now uses 6 voltsWarning: the radio will stop working!
可以发现,我们这里直接使用.voltage 而不是._voltage,这样就告诉python去使用property装饰的方法,我们可以通过使用@.setter and @.deleter 使属性变为read-only(只读),从而保护voltage不会被随意修改和删除
__slots__
classCelebrity:# 限定 Celebrity对象只能绑定name, age,domain属性,加速__slots__= ['name','age',"domain"]# Class Attribute species ='human'# Initializer / Instance Attributesdef__init__(self,name,age,domain): self.name = name self.age = age self.domain = domain
classCelebrity:# Class Attribute species ='human'__slots__= ['name','age']# Initializer / Instance Attributesdef__init__(self,name,age,domain): self.name = name self.age = age self.domain = domainfemale_leader =Celebrity("Miss Dong",65,"electrical appliance")# Access the instance attributesprint("{} is {}.".format( female_leader.name, female_leader.age))Out:AttributeError:'Celebrity'object has no attribute 'domain'
female_leader =Celebrity("Miss Dong", 65,"electrical appliance")male_leader =Celebrity("Jack Ma", 55,"internet")# Access the instance attributesprint("{} is {} and {} is {}.".format( female_leader.name, female_leader.age, male_leader.name, male_leader.age))# Is male_leader a human?if male_leader.species =="human":print("{0} is a {1}!".format(male_leader.name, male_leader.species))Out:Miss Dong is65and Jack Ma is55.Jack Ma is a human!
a =Celebrity("Miss Dong",65,"electrical appliance")b =Celebrity("Jack Ma", 55,"internet")c =Celebrity("Lei Jun", 50,"mobile")defget_oldest(*args):returnmax(args)print("The big brother is {} years old.".format(get_oldest(a.age, b.age, c.age)))Out:The big brother is65 years old.
Inheritance
首先,我们在Celebrity类中新增两个方法:
description:对生成的大佬简单描述
speak: 大佬发言
完成后的结果如下:
classCelebrity:__slots__= ['name','age',"domain"] species ='human'def__init__(self,name,age,domain): self.name = name self.age = age self.domain = domain# instance methoddefdescription(self):return"{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain)# instance methoddefspeak(self,sound):return"{} says {}".format(self.name, sound)
现在新建两个类InternetBoss,MobileBoss,全部继承于 Celebrity类:
# Child class (inherits from Dog() class)classInternetBoss(Celebrity):pass# Child class (inherits from Dog() class)classMobileBoss(Celebrity):pass
li.description()li.speak("What's your problem ?")Out:Robbin is50 years old, working in the advertisement industryRobbin says: What's your problem ?lei =MobileBoss("leijun", 50,"mobile")lei.speak("Are you ok ?")Out:leijun says: Are you ok ?
Polymorphisn & Override
classInternetBoss(Celebrity):defdescription(self):print("I'm Internet Boss !")classMobileBoss(Celebrity):defdescription(self):print("I'm Mobile phone Boss !")li =InternetBoss("Robbin",50,"advertisement")lei =MobileBoss("leijun", 50,"mobile")li.description()lei.description()Out:I'm Internet Boss !I'm Mobile phone Boss !
isinstance() & issubclass()
Python 有两个判断继承的函数:
isinstance() 用于检查实例类型
issubclass() 用于检查类继承
classCelebrity:__slots__= ['name','age',"domain"] species ='human'def__init__(self,name,age,domain): self.name = name self.age = age self.domain = domaindefdescription(self):print( "{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain))defspeak(self,sound):print("{} says: {}".format(self.name, sound))classInternetBoss(Celebrity):defdescription(self):print("I'm Internet Boss !")classMobileBoss(Celebrity):defdescription(self):print("I'm Mobile phone Boss !")mingzhu =Celebrity("Miss Dong",65,"electrical appliance")ma=InternetBoss("Pony", 48,"internet")lei =MobileBoss("leijun", 50,"mobile")# 现在使用issubclass()判断InternetBoss和MobileBoss是否继承自Celebrity:issubclass(InternetBoss,Celebrity)# Trueissubclass(MobileBoss,Celebrity)# True#使用isinstance()查看mingzhu到底是谁的实例:isinstance(mingzhu,Celebrity)# Trueisinstance(mingzhu,InternetBoss)# Falseisinstance(mingzhu,MobileBoss)# False#同理查看ma到底是哪个类的实例:isinstance(ma,Celebrity)# Trueisinstance(ma,InternetBoss)# Trueisinstance(ma,MobileBoss)# False
classInternetBoss(Celebrity):def__init__(self,name,age,domain,hometown):super().__init__(name, age, domain) self.hometown = hometowndefdescription(self):print("I'm Internet Boss !")def__repr__(self):returnf"This is {self.name} speaking !"