继承
编写类时,并非总是要从空白开始。如果你要编写的类是另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类,子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
1.子类的方法__init__()
创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。子类的方法__init__()需要父类施以援手。
比如:举例来模拟电动汽车。电动汽车是一种特殊的汽车,因此可以使用前面创建的Car类的基础上创建新类ElectricCar,这样我们就只需为电动汽车特有的属性和行为编写代码。
下面来创建一个简单的ElectricCar类版本,它具备Car类的所有功能:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + "miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
super().__init__(make,model,year)
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
2016 Tesla Model S
在创建子类时,父类必须包含在当前文件中,且位于子类前面。定义子类时,必须在括号内指定父类的名称。方法__init__()接受创建Car实例所需的信息。
super()是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让python调用ElectricCar的父类方法__init__(),让ElectricCar实例包含父类的所有属性。父类也称为超类(superclass)
2.Python2.7中的继承
在Python2.7中,继承语法稍有不同,ElectricCar类的定义类似于下面这样:
class Car(object):
def __init__(self,make,model,year):
--snip--
class ElectricCar(Car):
def __init__(self,make,model,year):
super(ElectricCar,self.__init__(make,model,year))
--snip--
函数super()需要两个实参:子类名和对象self。为帮助Python将父类和子类关联起来,这些实参必不可少。另外,在Python2.7中使用继承时,务必在定义父类时在括号内指定object。
3.给子类定义属性和方法
让一个类继承另一个类后,可添加区分子类和父类所需的新属性和方法。
下面来添加一个电动汽车特有的属性(电瓶),以及一个描述该属性的方法。我们将存储电瓶容量,并编写一个打印电瓶描述的方法:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + "miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
super().__init__(make,model,year)
self.battery_size = 70
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-KWh battery.")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
2016 Tesla Model S
This car has a 70-KWh battery.
对于ElectricCar类的特殊化程度没有任何限制。模拟电动汽车时,可以根据所需的准确程度添加任意数量的属性和方法。如果一个属性或方法是任何汽车都有的,而不是电动汽车特有的,就应该将其加入到Car类而不是ElectricCar类中。这样,使用Car类的人将获得相应的功能,而ElectricCar类只包含处理电动汽车特有属性和行为的代码。
4.重写父类的方法
对于父类的方法,只要它不符合子类模拟的实物行为,都可对其进行重写。为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名。这样,Python将不会考虑这个父类方法,而只关注在子类中定义的相应方法。
假设Car类有一个名为fill_gas_tank()的方法,它对全电动汽车来说毫无意义,因此可能想重写它。如下:
class ElectricCar(Car):
--snip--
def fill_gas_tank(self):
""" 电动汽车没有油箱 """
print("This car doesn't need a gas tank!")
现在,如果有人对电动汽车调用方法fill_gas_tank(),python将忽略Car类中的方法fill_gas_tank(),转而运行上述代码。使用继承时,可让子类保留从父类哪里继承而来的精华,并剔除不需要的。
5.将实例用作属性
使用代码模拟实物时,你可能会发现自己给类添加的细节越来越多:属性和方法清单以及文件都越来越长。这种情况下,可能需要将类的一部分作为一个独立的类提取出来。你可以将大型类拆分成多个协同工作的小类。
比如,不断给ElectricCar类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery的类中,并将一个Battery实例用作ElectricCar类的一个属性:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + "miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self,battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year)
"""
初始化父类的属性,在初始化电动汽车特有的属性
"""
super().__init__(make,model,year):
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
2016 Tesla Model S
This car has a 70-KWh battery.
定义了一个名为Battery的新类,它没有继承任何类,在新类中的方法__init__()除self外,还有另一个形参battery_size。这个形参是可选的:如果没有给它提供值,电瓶容量将被设置为70.
下面再给Battery类添加一个方法,它根据电瓶容量报告汽车的续航里程:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + "miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self,battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""
初始化父类的属性,在初始化电动汽车特有的属性
"""
super().__init__(make,model,year)
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
2016 Tesla Model S
This car has a 70-KWh battery.
This car can go approximately 240 miles on a full charge.
6.模拟实物
模拟较复杂的物件(如电动汽车)时,需要解决一些有趣的问题。续航里程是电瓶的属性还是汽车的属性呢?如果我们只需描述一辆汽车,那么将方法get_range()放在Battery类中也许是合适的;但如果要描述一家汽车制造商的整个产品线,也许应该将方法get_range()移到ElectricCar类中。在这种情况下,get_range()依然根据电瓶容量来确定续航里程,但报告的是一款汽车的续航里程。我们也可以这样做:将方法get_range()还留在Battery类中,但向它传递一个参数,如car_model;在这种情况下,方法get_range()将根据电瓶容量和汽车型号报告续航里程。
练习:
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.restaurant_name.title() + " : "+self.cuisine_type)
def open_restaurant(self):
print("the restaurant in operation.")
def how_many_peopel(self):
print("peopels are " + " " + str(self.number_served))
def set_number_served(self,value):
self.number_served = value
def increment_number_served(self,values):
self.number_served += values
print("the resturant maybe eating peopel:" + str(self.number_served))
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors = []
def correct_flavors(self,flavor):
self.flavors.append(flavor)
def show_flavors(self):
for flavor in self.flavors:
print("The ICE cream is : " + flavor)
new_icecream = IceCreamStand('bing xue qi yuan','icecream')
new_icecream.describe_restaurant()
new_icecream.correct_flavors('cao mei')
new_icecream.show_flavors()
new_icecream.correct_flavors('ping guo')
new_icecream.show_flavors()
Bing Xue Qi Yuan : icecream
The ICE cream is : cao mei
The ICE cream is : cao mei
The ICE cream is : ping guo
练习2:
class User():
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(self.first_name.title() + " " + self.last_name)
def greet_user(self):
print(self.first_name.title() + " " + self.last_name + " Hi!")
class Admin(User):
def __init__(self,first_name,last_name):
super().__init__(first_name,last_name)
self.privileges = ['can add post' , 'can delete post' , 'can ban user']
def show_privileges(self):
print( self.privileges)
Bob = User('li','Bob')
Bob.describe_user()
Bob.greet_user()
Aaron = Admin('YUn','aaron')
Aaron.describe_user()
Aaron.greet_user()
Aaron.show_privileges()
Li Bob
Li Bob Hi!
Yun aaron
Yun aaron Hi!
['can add post', 'can delete post', 'can ban user']
练习3:
class User():
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(self.first_name.title() + " " + self.last_name)
def greet_user(self):
print(self.first_name.title() + " " + self.last_name + " Hi!")
class Privileges():
def __init__(self):
self.privileges = ['can add post' , 'can delete post' , 'can ban user']
def show_privileges(self):
print(self.privileges)
class Admin(User):
def __init__(self,first_name,last_name):
super().__init__(first_name,last_name)
self.privileges = Privileges()
Bob = User('li','Bob')
Bob.describe_user()
Bob.greet_user()
Aaron = Admin('YUn','aaron')
Aaron.describe_user()
Aaron.greet_user()
Aaron.privileges.show_privileges()
Li Bob
Li Bob Hi!
Yun aaron
Yun aaron Hi!
['can add post', 'can delete post', 'can ban user']
练习4:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + "miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self,battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
if self.battery_size != 85:
self.battery_size = 85
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""
初始化父类的属性,在初始化电动汽车特有的属性
"""
super().__init__(make,model,year)
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
2016 Tesla Model S
This car has a 70-KWh battery.
This car can go approximately 240 miles on a full charge.
This car can go approximately 270 miles on a full charge.