Python reference problem

I am experiencing (for me) a very strange problem in Python.

I have a class called Menu: (snippet)

class Menu:
    """Shows a menu with the defined items"""
    menu_items = {}
    characters = map(chr, range(97, 123))

    def __init__(self, menu_items):
        self.init_menu(menu_items)

    def init_menu(self, menu_items):
        i = 0
        for item in menu_items:
            self.menu_items[self.characters[i]] = item
            i += 1

When I instantiate the class, I go to the list of dictionaries. Dictionaries are created using this function:

def menu_item(description, action=None):
    if action == None:
        action = lambda : None
    return {"description": description, "action": action}

And then the lists are created as follows:

t = [menu_item("abcd")]
m3 = menu.Menu(t)

a = [ menu_item("Test")]
m2 = menu.Menu(a)

b = [   menu_item("Update", m2.getAction),
                      menu_item("Add"),
                      menu_item("Delete")]
m = menu.Menu(b)

When I run my program, I get the same menu items every time. I started the program using PDB and found out, as soon as another instance of the class is created, the menu_items of all previous classes are set to the last list. It seems that the menu_items element is a static member.

What am I observing here?

+3
source share
2 answers

menu_items dict - , Menu. , :

class Menu:
    """Shows a menu with the defined items"""
    characters = map(chr, range(97, 123))

    def __init__(self, menu_items):
        self.menu_items = {}
        self.init_menu(menu_items)

    [...]

Python .

+16

Pär , : dict zip : -)

class Menu:
    """Shows a menu with the defined items"""
    characters = map(chr, range(97, 123))

    def __init__(self, menu_items):
        self.menu_items = dict(zip(self.characters, menu_items))
+5

Source: https://habr.com/ru/post/1725047/


All Articles