P155:冰淇淋小店是一种特殊的餐馆。编写一个名为 IceCreamStand 的类,让它继承你为完成练习 9-1 或练习 9-4 而编写的 Restaurant 类。这两个版本的Restaurant 类都可以,挑选你更喜欢的那个即可。添加一个名为 flavors 的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋的方法。创建一个IceCreamStand 实例,并调用这个方法。
代码如下:
class Restaurant:
"""一次模拟餐馆的简单尝试(9-1练习)"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name与cuisine_type"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""模拟餐馆描述内容"""
print(f"this is {self.restaurant_name} and {self.cuisine_type}")
def open_restaurant(self):
"""模拟餐馆打开时公告"""
print("now,restaurant is open")
class IceCreamStand(Restaurant):
"""子类IceCreamStand"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化父类属性"""
super().__init__(restaurant_name,cuisine_type)
"""给定子类特别属性"""
self.flavors = ["草莓味","西瓜味","奶油味"]
def read_flavors(self):
"""利用for循环来打印不同风味"""
for flavor in self.flavors:
print(f"this is {flavor}")
my_icecream = IceCreamStand("A-ICECREAM","ICE")
print(my_icecream.describe_restaurant())
my_icecream.read_flavors()
注:若用IDLE出现:SyntaxError: inconsistent use of tabs and spaces in indentation
则考虑将注释部分修改格式即可。(可以用删除加回车找到注释的合适位置。)
结果:
this is A-ICECREAM and ICE
this is 草莓味
this is 西瓜味
this is 奶油味
其他对于子类特别属性的代码方式还有可以在子类中单独增加一个函数,该函数采用在列表中增加元素的方式
class Restaurant:
--snip--
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors = ["草莓味","西瓜味","奶油味"]
def flavors(self):
self.flavors.append()
def read_flavors(self):
print(f"this is {self.flavors}")
"""用实例验证"""
my_icecream = IceCreamStand("A-ICECREAM","ICE")
my_icecream.read_flavors()
结果显示:
this is ['草莓味', '西瓜味', '奶油味']