Confused about the use of self in shopping cart exercise


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/1/5?curriculum_id=4f89dab3d788890003000096


 if not product in self.items_in_cart:
            self.items_in_cart[product] = price
            print product + " added."


In the above code, why is "self.items_in_cart[product] = price" used? Shouldn't it just be "items_in_cart[produt] = price"


#2

from this exercise we could deduce that items_in_cart is a member variable, agree? (just like is_alive in the exercise where this is explained)

member variables are automatically accessible to methods through self. This is why you use self


#3

so "self.product = product
self.price = price"
is not always necessary. It can be done in this format as well.


#4

yes, but member variables are the same for all instances of the object, this is not the case for variable you pass to __init__(), they can vary for every object instance


#5

that's my confusion. items_in_the_cart is a member variable and product and price are variables passed in add_items. Like in Override!
class Employee(object):
"""Models real-life employees!"""
def init(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

calculate_wage uses self.hours. I am confused when to use self. and when not. Please help me clear this.


#6

yes, and you pass price and add_item into __init__() so you can access them through self in all methods. Member variables (items_in_the_cart) are automatically added to self.

no? you make hours available through self in this line:

self.hours = hours

but this time, you don't do it in __init__(). you don't have to make variables through self in __init__() perse. you can do this in other methods as well. which is what you do in calculate_wage.


#7

yes, and you pass price and add_item into __init__() so you can access them through self in all methods. Member variables (items_in_the_cart) are automatically added to self.

so we use init() and self. so that we can access them in any method in the class. Right?


#8

yes, exactly


#9

thanks aton bro. :grinning:


#10