'dict'对象没有属性'append'


问题内容

我正在遵循有关设置班级的教程,以制作酒吧账单为例,但无法弄清楚为什么在向账单中添加新项目时出现错误

‘dict’对象没有属性’append’

编码

class Bar_tab:

    #dictionary
    menu = {
        'wine':5,
        'beer':2,
        'coke':3,
        'chicken':9,
        'dessert':7
    }

    #set up the class
    def __init__(self):
        #set up empty initial total and item list
        #customer will add items and total will add up
        #these variables will exist within the class
        self.total = 0
        self.items = {}

    #function for add items to tab
    def add(self,item):
        self.items.append(item)
        #add the value from menu dictionary for the 'item'
        self.total += self.menu[item]

    def pay_bill (self,tax,service):
        #tax will only exist within this function in the class
        tax=(tax/100) *self.total
        service=(service/100)*self.total
        total=self.total + tax + service

        for items in self.items:
            print(f'{item} ${self.menu[item]}')

        print(f'Total is ${total}')`

错误self.items.append(item)在线


问题答案:

self.item = {}初始化self.items为空字典。字典没有append()方法,因为它的主要目的是将键与值相关联。查看代码,目的是self.menu成为一个dict(将菜单项映射到价格)和self.items一个清单(票据项),并且list确实有一种append方法。

要初始化self.items为空列表,请将分配修改为:

self.item = []