I can't access some data formatted by a function using OOP in python:
class Menu:
"""Models the Menu with drinks."""
def __init__(self):
self.menu = [
MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
]
1. from menu import Menu
2. from coffee_maker import CoffeeMaker
3. from money_machine import MoneyMachine
4.
5. print("HOT COFFEE!")
6. print("Here is the coffee menu!")
7. menu1 = Menu()
8. mycoffee = CoffeeMaker()
9. print("Here are the resources available to make coffee!")
10. mycoffee.report()
11. order = input("Choose the type of coffee you want: ")
12. menu1.find_drink(order)
13. mymoney = MoneyMachine()
14. mymoney.process_coins()
15. mymoney.make_payment(**menu[order][cost]**)
16. if mymoney.make_payment() == True:
17. if mycoffee.is_resource_sufficient(order) == True:
18. mycoffee.make_coffee()
The bold text in line 15 is causing me headaches. I don't know how to access the cost in the Menu class.
I tried :
mymoney.make_payment(menu[order][cost])
CodePudding user response:
You can try to write a new function on the class which helps to get the cost information. Assuming MenuItem class has a private attribute named "cost" and Menu class can access its attributes
Class Menu:
.
.
.
def get_cost(self, drink):
return drink.cost
In your other script:
.
.
drink = menu1.find_drink(order) #its better to have a structure like this instead of calling the function directly.
order = Menu.get_cost(drink)
CodePudding user response:
I advice to use a dictionary object instead of a list object for the Menu.menu .
To be honest, I'm not sure I understood the question (maybe reformulate your question, or share more of your code), but assuming that MenuItem is a class as well, this could work to access the cost:
class Menu:
"""Models the Menu with drinks."""
def __init__(self):
self.menu = {
"latte": MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
"espresso": MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
"cappucino": MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
}
This way, you should be able to access the cost with Menu.menu[order].cost, or in your case (if I understood correctly), menu1.menu[order].cost
I hope it helped you, or it answered your question.