python2 vs python3函数到方法绑定

sth*_*ult 10 python-2.x python-3.x

亲爱的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
Run Code Online (Sandbox Code Playgroud)

使用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)
Run Code Online (Sandbox Code Playgroud)

所以我可以这样做:

B.method = UnboundMethodType(A().method)
B.method() # print both A and B instances
Run Code Online (Sandbox Code Playgroud)

没有写这样的描述符,有没有其他方法可以做到这一点?

TIA

She*_*ena 1

B.method = lambda o: A.method(o,A())

b = B()
b.method()
Run Code Online (Sandbox Code Playgroud)

b.method()然后线路会呼叫A.method(b,A())。这意味着每次都会初始化一个 A。为了避免这种情况:

a = A()
B.method = lambda o: A.method(o,a)
Run Code Online (Sandbox Code Playgroud)

现在,每次在 B 的任何实例上调用 b.method() 时,A 的同一个实例都会作为第二个参数传递。