0
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'

What am I doing wrong here? I feel the *args in calculate_value is causing issues, but I am unable to see the fault. Much thanks!

Maks
  • 21
  • 4

2 Answers2

2

You would need to loop over stuff to access each product that was passed

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

Output

>>> calculate_value(a, b)
13
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I see, python sees stuff here as a tuple automatically? – Maks Jun 10 '21 at 15:52
  • Basically, yes. Canonically these are referred to as [`*args` and `**kwargs`](https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs) and represent positional and named arguments respectively. – Cory Kramer Jun 10 '21 at 15:53
0

When you use *args (or *stuff) then it is a tuple of all of the arguments that are passed in (or technically all of the remaining arguments). So when you call calculate_value(...) with two arguments, stuff is now a tuple of two items. If you called 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` attribute.

saquintes
  • 1,074
  • 3
  • 11