属性错误:'tuple'对象没有属性'price' |*参数使用问题。我做错了什么?


class product():
def __init__(self, price, product_id, quantity):
self.price = price
self.product_id = product_id
self.quantity = quantity

def calculate_value(*stuff):
print(sum(stuff.price*stuff.quantity))

a = product(2,"a", 2)
b = product(3, "b", 3)
calculate_value(a,b)

Error: 
Traceback (most recent call last):
File "/Users/apple/Desktop/Python/product_inventory_project.py", 
line 17, in <module>
calculate_value(a,b)
File "/Users/apple/Desktop/Python/product_inventory_project.py", 
line 11, in calculate_value
print(sum(stuff.price*stuff.quantity))
AttributeError: 'tuple' object has no attribute 'price'

我在这里做错了什么?我觉得calculate_value中的*args导致了问题,但我看不出故障。非常感谢!

您需要在stuff上循环以访问传递的每个product

def calculate_value(*stuff):
return sum(i.price * i.quantity for i in stuff)

输出

>>> calculate_value(a, b)
13

当您使用*args(或*stuff(时,它是传入的所有参数(或者从技术上讲是所有剩余参数(的元组。因此,当您用两个参数调用calculate_value(...)时,stuff现在是两个项的元组。如果您将calculate_value(...) with one argument,的内容称为would be a tuple of one item. Regardless, you need to iterate (or something) over the tuple to get to the产品items you pass in. You are treating的内容like an instance of产品, but it's not. It's a tuple. Hence the error saying元组object has no价格`属性。

最新更新