首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AttributeError:'str‘对象没有属性'print_item_cost’

AttributeError:'str‘对象没有属性'print_item_cost’
EN

Stack Overflow用户
提问于 2019-09-10 05:25:43
回答 1查看 1K关注 0票数 0

在运行此代码时,我收到以下错误消息:

代码语言:javascript
复制
Traceback (most recent call last):
  File "main.py", line 33, in <module>
    item.print_item_cost()
AttributeError: 'str' object has no attribute 'print_item_cost'

我已经验证了属性是在对象中定义的,所以我不清楚为什么要抛出这个错误。

代码语言:javascript
复制
class ItemToPurchase:
    def __init__(self, name = 'none', price = 0, qty = 0):
        self.name = name
        self.price = price
        self.qty = qty

    def print_item_cost(self):
        print('%s %d @ $%d = $%d' % (self.name, self.qty, self.price, (self.price * self.qty))) 

    def calculate_subtotal(self):
        return self.price * self.qty

if __name__ == "__main__":
    i = 0
    order_list = []
    for i in range(2):
        print('Item %d' % int(i + 1))
        print('Enter the item name:')
        input_name = input()
        item = input_name
        item = ItemToPurchase()
        item.name = input_name        
        print('Enter the item price:')
        item.price = int(input())
        print('Enter the item quantity:')
        item.qty = int(input())
        order_list.append(input_name)

    print('\nTOTAL COST')
    total = 0
    for item in order_list:
        print(item, '\n')
        item.print_item_cost()
        total += item.calculate_subtotal()
    print('\nTotal: $%d' % total)

我提供的程序输入如下:

代码语言:javascript
复制
Chocolate Chips
3
1
Bottled Water
1
10

这将产生以下输出:

代码语言:javascript
复制
Item 1
Enter the item name:
Enter the item price:
Enter the item quantity:

Item 2
Enter the item name:
Enter the item price:
Enter the item quantity:

TOTAL COST
Chocolate Chips 1 @ $3 = $3
Bottled Water 10 @ $1 = $10

Total: $13
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-10 05:30:37

在列表中追加一个字符串,而不是item对象

代码语言:javascript
复制
input_name = input()
...
order_list.append(input_name)

然后翻阅那个列表,希望它不是字符串.

我建议稍微清理一下这个部分,这样您就可以实际调用类的构造函数了。

代码语言:javascript
复制
    print('Enter the item name:')
    input_name = input()

    print('Enter the item price:')
    price = int(input())

    print('Enter the item quantity:')
    qty = int(input())

    order_list.append(ItemToPurchase(input_name, price, qty))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57864474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档