Python:如何以不同类型参数调用未绑定方法?

5 投票
1 回答
3547 浏览
提问于 2025-04-16 01:37
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)
>>>

我该怎么做这个呢?

补充说明:这个例子更清楚了。

1 个回答

9

使用方法的 im_func 属性。

A.f.im_func(b)

撰写回答