简体   繁体   中英

Accessing a method from another class

Below is my code

class MenuItem:

    def __init__(self, name, wholesale_cost, selling_price):
        self._name = name
        self._wholesale_cost = wholesale_cost
        self._selling_price = selling_price

    def get_menuitem_name(self):
        return self._name

class LemonadeStand:

    def __init__(self, stand_name):
        self._stand_name = stand_name
        self._current_day = 0
        self._menu_dict = {}
        self._sales_list_objects = []

    def get_name(self):
        return self._stand_name

    def add_menu_item(self, menu_item):
        # takes as a parameter a MenuItem object and adds it to
        # the menu dictionary.

        x = MenuItem.get_menuitem_name()
        self._menu_dict[x] = menu_item

        self._menu_dict[menu_item.get_menuitem_name()] = menu_item

My question is, how is it possible to have the code below?

self._menu_dict[menu_item.get_menuitem_name()] = menu_item

To me, the below code makes more sense because get_menuitem_name() is in the MenuItem class. Therefore, MenuItem.get_menuitem_name() makes sense.

x = MenuItem.get_menuitem_name()
self._menu_dict[x] = menu_item

But in the self._menu_dict[menu_item.get_menuitem_name()] = menu_item , menu_item is a parameter of the add_menu_item() method in the LemonadeStand class.

So, I'm curious to know how it is possible to call the get_menuitem_name() method from the MenuItem class in the LemonadeStand class with just a parameter from the LemonadeStand class.

Look at the comments in the add_menu_item method - it takes "as a parameter a MenuItem object", that is an instance of the MenuItem class. From your question, it sounds like you need to do some learning about classes and how they're used. See, for example, the Python tutorial: https://docs.python.org/3/tutorial/classes.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM