Skip to main content
 首页 » 编程设计

python之调度一个类方法

2025年05月04日17zhwl

给定下面的一段代码,你如何正确地调度一个类方法:

>>> class A: 
...     def a(self): 
...         pass 
...     def b(self): 
...         pass 
...     c = a 
...     dispatch_map = { 'a' : a, 'b' : b } 
...     def dispatch(self, arg): 
...         self.dispatch_map[arg]()   # Fail: unbound method! 
>>> A().c 
<bound method A.a of <__main__.A object at 0x100550210>> 
>>> A().dispatch_map['a'] 
<function a at 0x10054acf8> 

为什么 c 是绑定(bind)方法,而 dispatch_map['a'] 是未绑定(bind)方法。 这对于普通函数来说很简单,并且是选择/大小写替换的常见习惯用法,使用类方法执行此操作的正确方法是什么?

请您参考如下方法:

只有当有一个实例要绑定(bind)到时,您才能绑定(bind)一个方法。您的调度映射仅使用类构建映射。

在__init__中构建 map :

def __init__(self): 
    self.dispatch_map = { 'a' : self.a, 'b' : self.b } 

或在您的 dispatch() 方法中显式绑定(bind)方法:

def dispatch(self, arg): 
    bound = self.dispatch_map[arg].__get__(self, type(self)) 
    bound() 

这使用了 descriptor protocol绑定(bind)方法,这是在实例上查找方法时通常发生的情况。