【问题标题】:AttributeError: 'str' object has no attribute 'name'AttributeError:“str”对象没有属性“name”
【发布时间】:2017-04-15 22:15:50
【问题描述】:
class System:
    def __init__(self,code,name,price):
        self.name = name
        self.price = price
        self.code = code

    def __str__(self):
        return 'Code: ' + self.code + '\tName: '  self.name + \'tPrice: ' + self.price 

    def choose_item(self):
        count = 0
        for item in self.name:
            print str(count) + '\t' item.name + '\t' + item.cost
            count += 1
        question = raw_input('Enter the code: ')
        if question == 0:
            exit()
        elif choice != self.code:
            print 'Invalid code'
        else:
            index = question -1
        name[index].self.choose_item()
        print 'Your item has been added'

我收到此错误,但看不到错误。我想通过键入代码来选择项目,以便添加项目。不确定这是正确的方法。

AttributeError: 'str' object has no attribute 'name'

【问题讨论】:

  • 不要更改原代码。保持错误,否则任何经历过这个的人都会对所提供的答案感到困惑。

标签: string python-2.7 object attributeerror


【解决方案1】:

前两个错误在这个函数__str__(self) 应该是'\tName: ' + self.name + '\tPrice: ' (您错过了+ 符号,并且没有在单引号内包含 \t。)

return 'Code: ' + self.code + '\tName: ' + self.name + '\tPrice: ' + self.price 

然后在choose_item(self) 函数中。 (缺少 + 号)

print str(count) + '\t' + item.name + '\t' + item.cost

【讨论】:

  • 谢谢@MarlonAbeykoon 我已经更改了代码,但仍然给我同样的错误。有什么修复代码的建议吗?
  • @Beginner 是否有效?如果是,请点击勾选接受答案。
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
相关资源
最近更新 更多