嗯,这就是问题所在,我有一个像这样的课程
Class MyClass(GuiWidget):
def __detectWhichItemClicked(self):
pass
def __handleRightClickItem1(self):
pass
def __handleRightClickItem2(self):
pass
def __handleRightClickItem3(self):
pass
def __handleRightClickItem4(self):
pass
__ detectWhichItemClicked是检查哪个项目被点击的功能,如果单击不同的项目,它将触发不同的进程,不同的进程在__handleRightClickItem *函数中实现。当代码更新时,可能会添加新的__handleRightClickItem *函数。
所以这样,我想把__handleRightClickItem *的“函数指针”改成dict, 如果dict属于MyClass实例,那么每个MyClass实例都会得到一个副本,这可能会浪费内存。如何将这些东西添加到类成员并在实例方法中调度__handleRightClickItem *,例如__detectWhichItemClicked。
我可能想要像这样实现它:
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我喜欢它像以前一样,但是,这可能不那么优雅,有人可以展示如何解决这个问题吗?
答案 0 :(得分:1)
更新:无法获得所需的语法,因为self.__class__.functionMap[itemName]
无法知道应该对哪个实例进行操作。但是,如果您明确传递self
,则可以非常接近:
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)
我不确定您想要哪些选项,但这是Python提供的。