代码之家  ›  专栏  ›  技术社区  ›  Ikke

Python引用问题

  •  3
  • Ikke  · 技术社区  · 16 年前

    我有一个叫做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
    

    当我实例化这个类时,我传入一个字典列表。使用此功能创建词典:

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

    然后创建列表,如下所示:

    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)
    

    当我运行我的程序时,我每次都会得到相同的菜单项。我用PDB运行了这个程序,发现一旦创建了一个类的另一个实例,以前所有类的菜单项都设置为最新列表。似乎菜单项成员是静态成员。

    2 回复  |  直到 16 年前
        1
  •  16
  •   Pär Wieslander    16 年前

    这个 menu_items 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 tutorial section on classes

        2
  •  5
  •   Jochen Ritzel    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))