【问题标题】:Python: How to call unbound method with other type parameter? [duplicate]Python:如何使用其他类型参数调用未绑定的方法? [复制]
【发布时间】:2010-07-21 07:11:55
【问题描述】:
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)
>>>

我该怎么做?

编辑:这个例子更清楚了

【问题讨论】:

  • 需要这样做是不寻常的。你是不是不能用staticmethod装饰器来解决你的问题?

标签: python methods


【解决方案1】:

使用方法的im_func属性。

A.f.im_func(b)

【讨论】:

  • 在 Python 2.6+ 中也可以使用A.f.__func__ (docs)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2013-12-26
  • 1970-01-01
相关资源
最近更新 更多