Home > Mobile >  Is it possible to input a list as an attribute to a method within a class?
Is it possible to input a list as an attribute to a method within a class?

Time:08-16

I am struggling on this Codecademy project. I am trying to input a list when calling a class object, to make my code more concise and practical, rather than having to explicitly define the list as a variable to be attributed to the method. I want the function "Menu.calculate_bill" to work in this way. Here is the code that I am trying to use:

class Menu:
  def __init__(self, name, items, start_time, end_time):
    self.name = name
    self.items = items
    self.start_time = start_time
    self.end_time = end_time
  
  def __repr__(self):
    return self.name   ' menu available from '   str(self.start_time)   ' o\'clock'   " to "   str(self.end_time)   ' o\'clock'
  

  def calculate_bill(self, purchased_items = []):
    total_price = 0
    for item in purchased_items:
      total_price  = self.name[item][0]
    return(total_price)

brunch = Menu('brunch', {'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}, 11, 16)

early_bird = Menu('early-bird', {'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00}, 15, 18)

dinner = Menu('dinner', {'crostini with eggplant caponata': 13.00, 'caesar salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00}, 17, 23)

kids = Menu('kids', {'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00}, 11, 21)

Menu.calculate_bill(['pancakes', 'home fries', 'coffee'])

CodePudding user response:

The prices are in self.items, not self.names. You don't need to use [0].

  def calculate_bill(self, purchased_items = []):
    total_price = 0
    for item in purchased_items:
      total_price  = self.items[item]
    return(total_price)

Since calculate_bill() is an instance method, you have to call it on an instance.

print(brunch.calculate_bill(['pancakes', 'home fries', 'coffee']))
  • Related