【问题标题】:AttributeError: 'tuple' object has no attribute 'price' | Issues with *args usage. What am I doing wrong?AttributeError: 'tuple' 对象没有属性 'price' | *args 使用问题。我究竟做错了什么?
【发布时间】:2021-06-10 15:46:36
【问题描述】:
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 引起了问题,但我看不到故障。非常感谢!

【问题讨论】:

    标签: python function class tuples args


    【解决方案1】:

    您需要遍历 stuff 才能访问每个传递的 product

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

    输出

    >>> calculate_value(a, b)
    13
    

    【讨论】:

    • 我明白了,python 自动将这里的东西视为一个元组?
    • 基本上,是的。典型地,这些被称为*args and **kwargs,分别代表位置和命名参数。
    【解决方案2】:

    当您使用*args(或*stuff)时,它是传入的所有参数(或技术上所有剩余参数)的元组。因此,当您使用两个参数调用 calculate_value(...) 时,stuff 现在是两个项目的元组。如果你打电话给calculate_value(...) with one argument, stuffwould be a tuple of one item. Regardless, you need to iterate (or something) over the tuple to get to theproductitems you pass in. You are treatingstufflike an instance ofproduct, but it's not. It's a tuple. Hence the error saying tupleobject has noprice`属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2021-01-18
      • 2012-07-17
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多