AttributeError:'Restaurant'对象没有属性'flavors' - 为什么?

时间:2018-03-01 14:54:31

标签: python class attributeerror

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

2 个答案:

答案 0 :(得分:1)

在其他初学者到来尝试用Python理解OOP中的属性错误/按大小顺序处理这些错误时,请关闭此循环:

  1. 检查您的缩进-方法需要在一个类中缩进(见下文)
  2. 继承的属性无需重新实例化(即 IceCreamStand 中的餐厅名称和美食类型无需在对super().__init__的调用之外进行实例化将它们添加到 Restaurant 类的__init__方法,并使其在 IceCreamStand 类中可以访问)
  3. 传递给方法的参数应像常规函数一样单独引用,除非您有意在调用方法时实例化属性(与创建对象并调用__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')