2010-07-21 101 views
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) 
>>> 

我該怎麼做?Python:如何使用其他類型參數調用unbound方法?

被修改:本實施例中更清晰

+0

需要這樣做是不常見的。你是不是可以使用'staticmethod'裝飾器來解決你的問題? – 2010-07-22 01:05:31

回答

8

使用該方法的im_func屬性。

A.f.im_func(b) 
+1

在Python 2.6+中,您也可以使用'A.f .__ func__'([docs](http://docs.python.org/2.6/reference/datamodel.html)) – 2012-11-14 09:47:37

相關問題