给定两个不相关的类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) 鉴于一类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)
所以,
奇怪的是,这在Python3中不再失败......