AttributeError:“ str”对象没有属性“ print_item_cost”

时间:2019-09-10 05:25:43

标签: python-3.x

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

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'

我已经验证了属性是在对象中定义的,所以我不清楚为什么会引发此错误。

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)

我提供的程序输入是:

Chocolate Chips
3
1
Bottled Water
1
10

应产生以下输出:

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

1 个答案:

答案 0 :(得分:1)

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

input_name = input()
...
order_list.append(input_name)

然后遍历该列表,希望它不是字符串...


我建议稍微清理一下该部分,以便您实际调用类的构造函数

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