调用子类方法,方法中使用for循环遍历元组,循环只执行一次打印出元组,不是预想的单个元素打印的效果。
代码
父类相关代码
class Restaurant:
"""餐馆的描述与营业状态"""
def __init__(self, restaurant_name, cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 8
def describle_restaurant(self):
"""描述餐馆的信息"""
print(f'The restaurant name is {self.restaurant_name}.')
print(f'There are {self.number_served} persons visited '
f'{self.restaurant_name}.')
print(f"{self.restaurant_name}'s type is {self.cuisine_type}.")
创建子类代码
class IceCreamStand(Restaurant):
"""冰淇淋子类继承餐馆父类"""
def __init__(self, restaurant_name, cuisine_type, *flavors):
"""
初始化父类属性,再初始化子类属性
"""
super().__init__(restaurant_name, cuisine_type)
self.flavors = flavors
def show_ice(self):
print(f"\nThe following is the kind of this icecream:")
for flavor in self.flavors:
print(f'{flavor}')
方法调用
kind = ('香草', '蓝莓', '柠檬', '西瓜', '草莓', '猫屎')
re = IceCreamStand('蜜雪冰城', '冰淇淋', kind)
re.describle_restaurant()
re.show_ice()
show_ice()是子类特有的方法,
执行结果
尝试解决,修改子类方法
def __init__(self, restaurant_name, cuisine_type):
"""
初始化父类属性,再初始化子类属性
"""
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
直接使用实例re.flavors = kind 传入实参得到预期结果
疑惑是为什么第一种方式不可以,是因为初始化父类属性时不能直接在_init_()方法中添加子类属性(不能的话,但是实参能传进去)。