实现此目的的一种方法是将可调用对象作为未绑定方法附加到类。方法构造函数will使用任意可调用对象(即具有__call__()
方法)——不仅仅是函数。
from types import MethodType
class Foo(object):
def __init__(self, name, val):
self.val = val
self.__name__ = name + '_foo'
self.name = name
def __call__(self, instance):
return self.name + str(self.val + instance.val)
class Baz(object):
def __init__(self, val):
self.val = val
Baz.biff = MethodType(Foo("biff", 42), None, Baz)
b = Baz(13)
print b.biff()
>>> biff55
在 Python 3 中,不存在未绑定实例方法(类只附加了常规函数)这样的东西,因此您可以将Foo
类一个描述符,通过给它一个返回绑定实例方法的描述符__get__()
方法。 (实际上,这种方法也适用于 Python 2.x,但上面的方法会表现得更好一些。)
from types import MethodType
class Foo(object):
def __init__(self, name, val):
self.name = name
self.val = val
self.__name__ = name + '_foo'
self.name = name
def __call__(self, instance):
return self.name + str(self.val + instance.val)
def __get__(self, instance, owner):
return MethodType(self, instance) if instance else self
# Python 2: MethodType(self, instance, owner)
class Baz(object):
def __init__(self, val):
self.val = val
Baz.biff = Foo("biff", 42)
b = Baz(13)
print b.biff()
>>> biff55