如果你要编写的类是另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称谓父类,而新类称为子类。子类除了继承父类的所有属性和方法,还可以定义自己的属性和方法。
1. 继承父类所有的属性和方法,也可以给子类定义属于自己的属性和方法,如下面例子所示
lass Restaurant: # ①
"""一次模拟餐馆的尝试"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("The restaurant name is: " + self.restaurant_name.title() +".")
print("The cuisine type is: " + self.cuisine_type.title() + ".")
def open_restaurant(self):
print(self.restaurant_name + " is openning for 24 hours.")
class IceCreamStand(Restaurant): # ②
"""冰淇淋小店的特色之处"""
def __init__(self, restaurant_name, cuisine_type): # ③
super().__init__(restaurant_name, cuisine_type) # ④
self.flavors = ['strawberry', 'chocolate', "buleberry", "raspberry"] # ⑤
def describe_flavors(self): # ⑥
"""关于利用属性self.flavors的方法"""
print("The taste of icecreams is as fallow: ")
for flavor in self.flavors:
print(flavor)
favorite_shop = IceCreamStand("kfc_icecream", "sweets") # 子类IceCreamStand的实例
favorite_shop.describe_restaurant() # 调用父类的方法describe_restaurant()
favorite_shop.open_restaurant() # 调用父类的方法open_restaurant()
favorite_shop.describe_flavors() # 调用子类才有的方法describe_flavors()
# 更多的讲解
# 1. 首先是类Restaurant的代码,如(①处)。**创建子类时,父类必须包含在当前文件中,且位于子类的前面**。
# 2. 定义子类IceCreamStand 时,必须在括号内指定父类的名称。如(②处)
# 3. 方法__init__(),接收创建Restaurant实例所需的信息。 (如③ 处)
# 4. super()是一个特殊的函数,帮助python把父类和子类关联起来。在④ 处的代码,让Python调用IceCreamStand的父类的方法__init__(),让子类IceCreamStand实例包含父类的所有属性。父类也称为超类(superclass).
# 在⑤处,创建了一个新的属性,self.flavors,并设置其默认值为一个列表。根据IceCreamStand类创建的所有实例都将包含这个属性,而所有Restaurant实例都不包含它。
# 在⑥处,创建了一个使用属性self.flavors()的方法。
# 输出结果为
The restaurant name is: Kfc_Icecream.
The cuisine type is: Sweets.
kfc_icecream is openning for 24 hours.
The taste of icecreams is as fallow:
strawberry
chocolate
buleberry
raspberry
2. 重写父类的方法
对于父类,如果它不符合子类实例的行为,都可进行重写。为此可在子类中定义一个这样的方法,即它与要重写父类的方法同名。这样,python将不会考虑这个父类的方法,而只关注你在子类中定义的相应方法。
3. 将实例用作属性,如下面的例子所示
class User: # 创建类User
"""一次模拟用户的简单尝试"""
def __init__(self, first_name, last_name, working_place):
"""初始化属性first_name, last_name 和 working_place"""
self.first_name = first_name
self.last_name = last_name
self.working_place = working_place
self.login_attempts = 0
def describe_user(self):
"""描述用户的基本用户信息"""
print("The user's first name is " + self.first_name.title() + ".")
print("The user's last name is " + self.last_name.title() + ".")
print("The user's working place is " + self.working_place.title() + ".")
def greet_user(self):
"""向用户打招呼"""
print("Good morning! " + self.first_name + " " + self.last_name)
def increment_login_attempts(self, login):
"""将属性login_attempts的值加1"""
self.login_attempts += login
print("当前登录的人数为 " + str(self.login_attempts))
class Privileges: # 创建类Privileges
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user'] # ③
def show_privileges(self):
print("The administrator has the following privileges: ")
for privilege in self.privileges:
print(privilege)
class Admin(User): # 创建类Admin,该类是User类的子类
def __init__(self, first_name, last_name, working_place):
super().__init__(first_name, last_name, working_place)
self.rights = Privileges() # ①
first_admin = Admin("meng", "chen", "canton") # 创建Admin的实例
first_admin.rights.show_privileges() # ②
# 更多的解释
# 在①处,我们定义了一个名为self.rights的属性。在①处的代码让python创建一个新的Privileges实例(由于没有指定任何实参,因此使用③处指定的默认值),并将该实例存储在属性self.rights中。
# 在②处的代码让Python在实例first_admin中查找属性rights,并将存储在该属性中的Privileges实例调用方法show_privileges()。
# 输出结果为:
The administrator has the following privileges:
can add post
can delete post
can ban user