【发布时间】:2019-03-11 14:31:30
【问题描述】:
我正在关注关于设置类的教程,以制作酒吧账单的示例,但无法弄清楚为什么在向账单添加新项目时出现错误
'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) 行出错
【问题讨论】:
-
append()通常用于列表,而不是字典,因为它们没有排序。你还需要一个键和一个值,你只有item。再次检查您的教程! -
self.items是一本字典。让它成为一个列表,它应该可以工作(将self.item = {}更改为self.item = [])。 -
那也应该是
for item in self.items:
标签: python python-3.x