【问题标题】:'dict' object has no attribute 'append''dict' 对象没有属性 'append'
【发布时间】: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


【解决方案1】:

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

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

self.item = []

【讨论】:

  • 感谢cmets的回答!我将 self.items 编辑为一个列表,但我得到了另一个错误 AttributeError: 'Bar_tab' object has no attribute 'append'。我只改变了那部分 def __init__(self): self.total = 0 self.items = []
  • @NoodlexPoodle 请不要采取错误的方式,但您需要注意 StackOverflow 不能替代学习资料 - 我们的想法不是我们为您调试您的代码,而是我们帮助您解决可能与他人相关的具体问题。如果您愿意,您可以提出一个单独的问题,但请先尝试自己调试问题,或通过 Python 教程进行操作。
  • 好的,知道了。当完全相同的代码在 youtube 视频上运行但不是在我这边时,我感到非常困惑。到时候我会自己想办法。感谢您的回复!
  • @NoodlexPoodle 没问题,很高兴为您提供帮助。如果此问题得到解决,请考虑accepting 的答案。
  • 我今天尝试后不知何故奏效了!谢谢。我认为可能是因为当我之前尝试过时,我在编辑代码后没有退出并重新启动终端,因此终端中的代码缓存没有改变。谢谢
猜你喜欢
  • 2019-03-31
  • 2016-02-11
  • 2018-06-22
  • 1970-01-01
  • 2020-11-07
  • 2020-10-16
  • 2021-05-26
  • 2020-12-08
  • 2019-11-16
相关资源
最近更新 更多