Basta Fazoolin' - Classes

Basta Fazoolin’ Project Link: Basta Fazoolin’ Link

Topic: Classes - Instance Variables, Methods

Hello, I am having trouble understanding the instance variable concept. Please look at the follow code from the Basta Fazoolin’ project:

def calculate_bill(self, purchased_items):
bill= 0
for purchased_item in purhcased_items:
if purchased_item in self.items:
bill += self.items[purchased_item]

return bill

***Menu dictionaries are below and outside of the dictionary

Included inside of the method calculate_bill for the menu class, there is an if statement. The purpose of this if statement is to check if the item is on one of the menus. However, I am confused how Python knows how to check the menu dictionaries that are listed outside of the class method by checking the instance variable self.items. The “items” variable is not used anywhere else in the project. Could someone please explain how python knows how to check the menus? I am also confused by the line: bill += self.items[purchased_item]. Can someone explain the indexing on this for me?

self.items is used in the constructor, it should store a dictionary where the keys are strings (something on the menu) and the values are numbers [floats] (which are the corresponding prices).

An example of such a dictionary is this:

brunch_items = {
    'pancakes': 7.50, 
    'waffles': 9.00, 
    'burger': 11.00, 
    'home fries': 4.50, 
    'coffee': 1.50, 
    'espresso': 3.00, 
    'tea': 1.00, 
    'mimosa': 10.50, 
    'orange juice': 3.50
}

and the constructor for Menu should be

  def __init__(self, name, items, start_time, end_time):
    self.name = name
    self.items = items #dictionary of menu item, price
    self.start_time = start_time
    self.end_time = end_time

so that you can do something like
brunch = Menu("Brunch", brunch_items, 11, 16)

The first argument of the method, self, is the object (the instance of the class), so every method of the class has access to self. Therefore, self.items can be accessed by any method of the class.

The indexing used in
self.items[purchased_item]
is what is used to get the value of a dictionary,
just like
brunch_items["pancakes"]
would give you 7.50 or 7.5
in the dictionary shown earlier.

2 Likes