亲爱的 python 3 专家,
使用 python2,可以执行以下操作(我知道这有点麻烦,但这不是重点:p):
class A(object):
def method(self, other):
print self, other
class B(object): pass
B.method = types.MethodType(A().method, None, B)
B.method() # print both A and B instances
使用 python3,没有更多未绑定的方法,只有函数。如果我想要相同的行为,听起来我必须引入一个自定义描述符,例如:
class UnboundMethod:
"""unbound method wrapper necessary for python3 where we can't turn
arbitrary object into a method (no more unbound method and only function
are turned automatically to method when accessed through an instance)
"""
def __init__(self, callable):
self.callable = callable
def __get__(self, instance, objtype):
if instance is None:
return self.callable
return types.MethodType(self.callable, instance)
所以我可以这样做:
B.method = UnboundMethodType(A().method)
B.method() # print both A and B instances
有没有其他方法可以在不写这样的描述符的情况下做到这一点?
TIA