Reputation: 1940
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?
Upvotes: 0
Views: 3275
Reputation: 281594
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.
Upvotes: 2