开发者

Python: How to call unbound method with other type parameter? [duplicate]

开发者 https://www.devze.com 2023-01-08 09:10 出处:网络
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?
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 answers) Closed 7 years ago.
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)
>>>

How can I do this?

Edited:this example is more clear


Use the im_func attribute of the method.

A.f.im_func(b)
0

精彩评论

暂无评论...
验证码 换一张
取 消