## class restaurant ##
实施超类
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print('This restaurant is called ' + self.restaurant_name + '.')
print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.')
def open_restaurant(self, hours):
self.hours = hours
print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!')
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
flavours = ['chocolate', 'vanilia', 'strawberry', 'lime', 'orange']
def flavours(self):
print('Available flavours: ')
for flavour in flavours:
print(flavour)
IceCreamStand = Restaurant(' Matt IceCream ', 'ice creams')
IceCreamStand.describe_restaurant()
IceCreamStand.flavours()
答案 0 :(得分:1)
在其他初学者到来尝试用Python理解OOP中的属性错误/按大小顺序处理这些错误时,请关闭此循环:
super().__init__
的调用之外进行实例化将它们添加到 Restaurant 类的__init__
方法,并使其在 IceCreamStand 类中可以访问)__init__
方法相反) )有关更改/运行代码,请参见下文:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print('This restaurant is called ' + self.restaurant_name + '.')
print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.')
def open_restaurant(self, hours):
print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!')
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavours = \
['chocolate', 'vanilia', 'strawberry', 'lime', 'orange']
def flavours(self):
print('Available flavours: ')
for flavour in self.flavours:
print(flavour)
stand = IceCreamStand(' Matt IceCream ', 'ice creams')
stand.describe_restaurant()
stand.flavours()
答案 1 :(得分:0)
因为Restaurant
确实没有属性flavours
; IceCreamStand
确实,或者至少做过,直到您使用Restaurant
IceCreamStand = Restaurant(...)
的实例替换了该类。
使用不同的变量名称(类名为camel-case,对象为初始小写的snake-case),并创建IceCreamStand
的实例。
ice_cream_stand = IceCreamStand(' Matt IceCream ', 'ice creams')