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

时间:2018-10-06 07:00:33

标签: python python-3.x

我正在遵循有关设置班级示例的教程,该示例制作了条形票据,却无法弄清楚为什么在向票据中添加新项目时会出错

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

1 个答案:

答案 0 :(得分:1)

self.item = {}self.items初始化为空的dictionary。字典没有append()方法,因为它的主要目的是将键与值相关联。查看代码,目的是将self.menu用作字典(将菜单项映射到价格),将self.items用作list(票据项),而{{1} }确实有append方法。

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

self.items