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

Jak mogę to zrobić?Python: Jak wywołać metodę niezwiązaną z innym parametrem typu?

Zmieniano: w tym przykładzie jest bardziej jasne

+0

Niezwykle trzeba to zrobić. Czy nie możesz użyć dekoratora 'staticmethod' do rozwiązania problemu? –

Odpowiedz

8

pomocą cechą sposobu im_func.

A.f.im_func(b) 
+1

W Pythonie 2.6+ możesz również użyć funkcji "A.f .__ func__" ([docs] (http://docs.python.org/2.6/reference/datamodel.html)) –

Powiązane problemy