AttributeError:“餐厅”对象没有属性“风味” - 为什么?

问题描述 投票:0回答:2
## 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()
python class attributeerror
2个回答
1
投票

因为

Restaurant
确实没有属性
flavours
IceCreamStand
会,或者至少会,直到您用
Restaurant
的实例替换该类并使用
IceCreamStand = Restaurant(...)

使用不同的变量名称(类名采用驼峰式命名,对象采用首字母小写的蛇形命名法),并创建

IceCreamStand
的实例。

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

1
投票

关闭此循环,以防其他初学者试图理解 Python 中 OOP 的属性错误/按数量级解决这些错误:

  1. 检查你的缩进 - 方法需要在类中缩进(见下文)
  2. 继承的属性不需要重新实例化(即 IceCreamStand 中的餐厅名称和美食类型不需要在调用
    super().__init__
    之外实例化,因为这会将它们传递给
    __init__
    方法) Restaurant 类,并使其可以在 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()
© www.soinside.com 2019 - 2024. All rights reserved.