class Car:
wheels = 0
def __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 yellow
It has 0 wheels
It 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 yellow
It has 0 wheels
My other car is red
It has 0 wheels
# Change the class variable value
Car.wheels = 4
print(f"My car has {my_car.wheels} wheels")
print(f"My other car has {my_other_car.wheels} wheels")
Out:
My car has 4 wheels
My other car has 4 wheels
# Change the instance variable value for my_car
my_car.wheels = 5
print(f"My car has {my_car.wheels} wheels")
print(f"My other car has {my_other_car.wheels} wheels")
Out:
My car has 5 wheels
My other car has 4 wheels
class Car:
wheels = 0
def __init__(self, color, model, year):
self.color = color
self.model = model
self.year = year
self._cupholders = 6
my_car = Car("yellow", "Beetle", "1969")
print(f"It was built in {my_car.year}")
Out:
It was built in 1969
my_car.year = 1966
print(f"It was built in {my_car.year}")
print(f"It has {my_car._cupholders} cupholders.")
Out:
It was built in 1966
It has 6 cupholders.
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 in 1969
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-108-1efe56f0c054> in <module>
1 my_car = Car("yellow", "Beetle", "1969")
2 print(f"It was built in {my_car.year}")
----> 3 print(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 = 2003
print(f"It was built in {my_car.year}")
del my_car.year
print(f"It was built in {my_car.year}")
Out:
My car was built in 1969
It was built in 2003
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-110-46914b0bae82> in <module>
6
7 del my_car.year
----> 8 print(f"It was built in {my_car.year}")
AttributeError: 'Car' object has no attribute 'year'
class Car:
def __init__(self, color, model, year):
self.color = color
self.model = model
self.year = year
self._voltage = 12
@property
def voltage(self):
return self._voltage
@voltage.setter
def voltage(self, volts):
print("Warning: this can cause problems!")
self._voltage = volts
@voltage.deleter
def voltage(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 = 6
print(f"My car now uses {my_car.voltage} volts")
del my_car.voltage
Out:
My car uses 12 volts
Warning: this can cause problems!
My car now uses 6 volts
Warning: the radio will stop working!
可以发现,我们这里直接使用.voltage 而不是._voltage,这样就告诉python去使用property装饰的方法,我们可以通过使用@.setter and @.deleter 使属性变为read-only(只读),从而保护voltage不会被随意修改和删除
__slots__
class Celebrity:
# 限定 Celebrity对象只能绑定name, age,domain属性,加速
__slots__ = ['name','age',"domain"]
# Class Attribute
species = 'human'
# Initializer / Instance Attributes
def __init__(self, name, age, domain):
self.name = name
self.age = age
self.domain = domain
female_leader = Celebrity("Miss Dong", 65,"electrical appliance")
male_leader = Celebrity("Jack Ma", 55,"internet")
# Access the instance attributes
print("{} 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 is 65 and Jack Ma is 55.
Jack Ma is a human!
a = Celebrity("Miss Dong",65,"electrical appliance")
b = Celebrity("Jack Ma", 55,"internet")
c = Celebrity("Lei Jun", 50,"mobile")
def get_oldest(*args):
return max(args)
print("The big brother is {} years old.".format(get_oldest(a.age, b.age, c.age)))
Out:
The big brother is 65 years old.
Inheritance
首先,我们在Celebrity类中新增两个方法:
description:对生成的大佬简单描述
speak: 大佬发言
完成后的结果如下:
class Celebrity:
__slots__ = ['name', 'age',"domain"]
species = 'human'
def __init__(self, name, age, domain):
self.name = name
self.age = age
self.domain = domain
# instance method
def description(self):
return "{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
现在新建两个类InternetBoss,MobileBoss,全部继承于 Celebrity类:
# Child class (inherits from Dog() class)
class InternetBoss(Celebrity):
pass
# Child class (inherits from Dog() class)
class MobileBoss(Celebrity):
pass
li.description()
li.speak("What's your problem ?")
Out:
Robbin is 50 years old, working in the advertisement industry
Robbin says: What's your problem ?
lei = MobileBoss("leijun", 50,"mobile")
lei.speak("Are you ok ?")
Out:
leijun says: Are you ok ?
Polymorphisn & Override
class InternetBoss(Celebrity):
def description(self):
print("I'm Internet Boss !")
class MobileBoss(Celebrity):
def description(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() 用于检查类继承
class Celebrity:
__slots__ = ['name', 'age',"domain"]
species = 'human'
def __init__(self, name, age, domain):
self.name = name
self.age = age
self.domain = domain
def description(self):
print( "{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain))
def speak(self, sound):
print("{} says: {}".format(self.name, sound))
class InternetBoss(Celebrity):
def description(self):
print("I'm Internet Boss !")
class MobileBoss(Celebrity):
def description(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)
# True
issubclass(MobileBoss,Celebrity)
# True
#使用isinstance()查看mingzhu到底是谁的实例:
isinstance(mingzhu,Celebrity)
# True
isinstance(mingzhu,InternetBoss)
# False
isinstance(mingzhu,MobileBoss)
# False
#同理查看ma到底是哪个类的实例:
isinstance(ma,Celebrity)
# True
isinstance(ma,InternetBoss)
# True
isinstance(ma,MobileBoss)
# False