This question already has answers here:
In Python, can you call an instance method of class A, but pass in an instance of class B?
(4个答案)
5年前关闭。
我怎样才能做到这一点?
编辑:这个例子更清晰
(4个答案)
5年前关闭。
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def f(self):
... print self.k
...
>>> class B(object):pass
...
>>> a=A()
>>> b=B()
>>> a.k="a.k"
>>> b.k="b.k"
>>> a.f()
a.k
>>> A.f(a)
a.k
>>> A.f(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with A instance as first argument (got B instance instead)
>>>
我怎样才能做到这一点?
编辑:这个例子更清晰
最佳答案
使用方法的im_func
属性。
A.f.im_func(b)
关于Python:如何使用其他类型参数调用未绑定(bind)方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3296993/