10

亲爱的 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

4

2 回答 2

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 的相同实例作为第二个参数传递。

于 2012-11-07T21:31:44.077 回答
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>
于 2015-05-12T08:48:20.073 回答