简体   繁体   中英

In python ,how to add class member function pointer in class member?

Well , this is the problem, I have a class like this

Class MyClass(GuiWidget):

   def __detectWhichItemClicked(self):
      pass

   def __handleRightClickItem1(self):
      pass

   def __handleRightClickItem2(self):
      pass

   def __handleRightClickItem3(self):
      pass

   def __handleRightClickItem4(self):
      pass

__detectWhichItemClicked is the function to check which item has been clicked , if clicked on different item , it will trigger different process, the different process is implemented in __handleRightClickItem* function . When the code updated, may be new __handleRightClickItem* function will be added.

So In this way , I want to the "function pointer" of __handleRightClickItem* to a dict, if the dict is owned by the MyClass instance, then each MyClass instance will got a copy, that may be a waste of memory. How can I add this things to a class member and dispatch the __handleRightClickItem* in instance method such as __detectWhichItemClicked.

I may want to implement it like this:

class MyClass:
    functionMap = {
                  "ITEM1": __handleRightClickItem1, //how can i add instance method to class member
                  "ITEM2": __handleRightClickItem2, 
                  "ITEM3":....
                  };

 def __detechWhichItemClicked(self):
    itemName = getItemName()
    if itemName in self.__class__.functionMap.keys():
        self.__class__.functionMap[itemName](arg)

Problay I prefer it to impl like before, however, this maybe not so elegant, can someone show how to solve this?

UPDATE : There's no way to get the syntax you want, since there's no way for self.__class__.functionMap[itemName] to know which instance it should operate on. However, if you pass self explicitly, you can get very close:

class MyClass:
    def __detectWhichItemClicked(self):
        itemName = getItemName()
        if itemName in self.functionMap:
            # Pass self into the call
            self.functionMap[itemName](self, arg)
    ...
    # This goes after the __handle methods are defined.
    functionMap = {
        "ITEM1": __handleRightClickItem1,
        ...
    }

# Equivalent.
getattr(obj, "foo")(arg)
getattr(MyClass, "foo")(obj, arg)
obj.foo(arg)
MyClass.foo(obj, arg)

# Also equivalent
bound_method = obj.foo # or getattr(obj, "foo")
bound_method(arg)

# Still equivalent
unbound_method = MyClass.foo # or getattr(MyClass, "foo")
unbound_method(obj, arg)

I'm not sure which of these options you want, but this is what Python offers.

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