亲爱的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
答案 0 :(得分:1)
B.method = lambda o: A.method(o,A())
b = B()
b.method()
行b.method()
然后调用A.method(b,A())
。这意味着每次都会初始化A.为了避免这种情况:
a = A()
B.method = lambda o: A.method(o,a)
现在每次在B的任何一个实例上调用b.method()时,都会传递相同的A实例作为第二个参数。
答案 1 :(得分:0)
嗯,你的代码在Python 2中也不起作用,但我得到了你想要做的。您可以使用lambda,如Sheena的答案或functools.partial。
>>> import types
>>> from functools import partial
>>> class A(object):
... def method(self, other):
... print self, other
...
>>> class B(object): pass
...
>>> B.method = partial(A().method, A())
>>> B().method()
<__main__.A object at 0x112f590> <__main__.A object at 0x1132190>