Skip to main content
 首页 » 编程设计

python之如何将部分函数绑定(bind)为 Python 类实例上的方法

2025年01月19日8jyk

我想将此函数绑定(bind)为某个类的方法:

def foo_method(msg, self): 
    print self.prefix + msg 

这个有效:

class A(object): 
    prefix = 'msg: ' 
 
A.foo = lambda *args: foo_method('hello', *args) 
 
A().foo() 
# => msg: hello 

然而,这不会:

from functools import partial 
 
class B(object): 
    prefix = 'msg: ' 
 
B.foo = partial(foo_method, 'hello') 
 
B().foo() 
# => TypeError: foo_method() takes exactly 2 arguments (1 given) 

第一个示例似乎绑定(bind)正确,而第二个则没有。

为什么?

请您参考如下方法:

答案是:描述符!自绑定(bind)仅在属性访问期间发生。方法没有特殊的语言支持 - 它们仅使用函数对象和描述符工作。

引用 https://docs.python.org/2/howto/descriptor.html#functions-and-methods :

Class dictionaries store methods as functions. [...] To support method calls, functions include the __get__() method for binding methods during attribute access. This means that all functions are non-data descriptors which return bound or unbound methods depending whether they are invoked from an object or a class. In pure python, it works like this:

class Function(object): 
    def __get__(self, obj, objtype=None): 
        "Simulate func_descr_get() in Objects/funcobject.c" 
        return types.MethodType(self, obj, objtype) 

迷人!

当访问A().foo时,会调用描述符机制,调用foo_method.__get__,返回绑定(bind)方法:

A().foo 
# => <bound method A.<lambda> of <__main__.A object at 0x10ca9c0d0>> 

因为 functools.partial 没有实现 __get__,所以它没有被绑定(bind):

B().foo 
# => <functools.partial at 0x10caf3aa0> 
 
hasattr(partial(foo_method, 'hello'), '__get__') 
# => False 

问题仍然存在:如果它如此简单,为什么 不 functools.partial 也实现它?