相关疑难解决方法(0)

将方法应用于另一个类的对象

给定两个不相关的类A和B,如何A.method使用B的对象调用self

class A:
    def __init__(self, x):
        self.x = x

    def print_x(self):
        print self.x

class B:
    def __init__(self, x):
        self.x = x

a = A('spam')
b = B('eggs')

a.print_x() #<-- spam
<magic>(A.print_x, b) #<-- 'eggs'
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
1
解决办法
1844
查看次数

如何将一个类的实例方法monkeypatch到另一个类?

鉴于一类A我只是可以添加一个instancemethod a通过

def a(self):
    pass

A.a = a
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试添加另一个类B的instancemethod b,即A.b = B.b调用的尝试A().b()产生一个

TypeError:b()必须使用B实例作为第一个参数调用unbound方法(没有任何东西)

(虽然B().b()很好).确实存在差异

A.a -> <unbound method A.a>
A.b -> <unbound method B.b>  # should be A.b, not B.b
Run Code Online (Sandbox Code Playgroud)

所以,

  • 如何解决这个问题?
  • 为什么会这样?它似乎不直观,但通常Guido有一些很好的理由......

奇怪的是,这在Python3中不再失败......

python monkeypatching python-2.x instance-methods

5
推荐指数
1
解决办法
586
查看次数