Search code examples
pythonclassvariablesmethodstypeerror

TypeError: Cart.add() missing 1 required positional argument: 'food'


I am trying to run my shopping cart using Python, but I am getting a TypeError that does not make sense because I've assigned a food item quantity to a variable and passed the variable into the method, but I am still getting the error.

Error:

File "/Users/adonairomero/Documents/codingTemple/week3/day1/homework/homework.py", line 73, in <module>
    Cart.add(food1)
TypeError: Cart.add() missing 1 required positional argument: 'food'

My code here


Solution

  • The problem here is that you're using

    Cart.add(food1)

    Cart is not an object but is the whole class. In Python, when you define a method of a class as

    class Example:
        def foo(self, a):
           # ...
    

    you are saying that in order to call foo you will require an object of class Foo, which is self and an attribute a. Python automatically detects as self the object on which you call the method, for example:

    instanceOfExample = Example()
    a = 5
    instanceOfExample.foo(a)
    

    would be the same as doing:

    instanceOfExample = Example()
    a = 5
    Example.foo(instanceOfExample, a)
    

    Back to your code, by calling

    Cart.add(food1)

    you are giving a value for the first parameter of the function add defined by the class Cart, which is self and not food!

    The correct way to do that would be:

    food1 = food("Apples", 8)
    cart = Cart()
    
    # Either one of the following
    cart.add(food1) # Here "self" is implicit
    Cart.add(cart, food1) # Here "self" is explicit
    

    EDIT: I just tried to explain how self works, but the fact that you "can do in both ways" doesn't mean that both ways are best practices.