It's not All Animals and Fruits


Can anyone explain me why self isn't being used in method "add_item" and "remove_item" for "product" and "price" variables?

class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def init(self, customer_name):
self.customer_name = customer_name

def add_item(self, product, price):
    """Add product to the cart."""
    if not product in self.items_in_cart:
        self.items_in_cart[product] = price
        print product + " added."
        print product + " is already in the cart."

def remove_item(self, product):
    """Remove product from the cart."""
    if product in self.items_in_cart:
        del self.items_in_cart[product]
        print product + " removed."
        print product + " is not in the cart."


If I understand your question, you're wondering why if

def remove_item(self, product):

has two arguments, we only call it with one? ---


I think the reason is that with Classes, Objects in that Class already send self as an argument to the function automatically.

For example, if we write


and forget to add a price as a second argument, we get the error

TypeError: add_item() takes exactly 3 arguments (2 given)

But of course we only consciously gave one argument ("Apple"); (self) was sent automatically, and we forgot the third one (price).

If we write

my_cart.add_item("Apple", 3.99)

the function works as it should.

I hope that helps (or you or someone else can correct me if I'm mistaken! ) :wink: