AttributeError: 'Restaurant' object has no attribute 'flavours' - why?

AttributeError: 'Restaurant' object has no attribute 'flavours' - why?

## class restaurant ##

Implemented superclass

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()

因为Restaurant,的确,没有属性flavoursIceCreamStand 会,或者至少会,直到您将 class 替换为 RestaurantIceCreamStand = Restaurant(...) 的实例。

使用不同的变量名称(camel-case 用于 class 名称,snake-case 首字母小写用于对象),并创建 IceCreamStand.[=17 的实例=]

ice_cream_stand = IceCreamStand(' Matt IceCream ', 'ice creams')

关闭这个循环,以防其他初学者尝试理解 Python/tackling 中 OOP 的属性错误,这些错误按数量级排列:

  1. 检查缩进 - 方法需要在 class 内缩进(见下文)
  2. 继承的属性不需要 re-instantiated(即 IceCreamStand 中的餐厅名称和美食类型不需要在调用 super().__init__ 因为这会将它们传递给 Restaurant class 的 __init__ 方法,并使它们可以在 IceCreamStand[=26= 中访问] class)
  3. 传递给方法的参数应该像常规函数一样被自己引用,除非你有意想在调用方法时实例化属性(而不是在创建对象和 __init__ 方法时被称为)

请参阅下面的 changes/running 代码:

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()