2011-08-25 17 views
1

我要Calling a function of a module from a string with the function's name in Python但每當我打電話給我的班級我的程序它給我這個錯誤:類型錯誤:未綁定的方法bar()必須以foo例如被稱爲第一個參數(什麼都沒有代替)誤差GETATTR

有人可以幫我

+2

向我們顯示您的代碼。 – NPE

+0

確實需要查看代碼才能確定,但​​聽起來像您正在調用某個類的成員,而該方法不是[classmethod](http://docs.python.org/library/functions.html#classmethod )。 –

回答

8

這是一個典型的情況,它會產生你描述的問題。

class Foo(object): 
    def bar(self,x): 
     print(x) 

foo=Foo() 

調用gettatrr(Foo,'bar')返回不受約束的方法,Foo.bar

getattr(Foo,'bar')(1) 

導致

TypeError: unbound method bar() must be called with Foo instance as first argument (got int instance instead)

的方法,Foo.bar,是因爲沒有實例(如foo)打算調用時被作爲第一個參數提供,稱爲「未結合」。畢竟,當僅僅提供Foo類時,怎麼可能?

在另一方面,如果提供的類的實例:

getattr(foo,'bar')(1) 

產生

1 

因爲foo.bar是「結合」的方法 - 將foo作爲第一供給當調用foo.bar時參數。

PS。您的錯誤消息說:「......用foo實例調用......」。與上面發佈的錯誤消息相比,您的班級似乎被稱爲小寫foo。請注意,PEP8 style guide建議始終使用大寫字母命名類,並使用小寫字母命名實例。這樣做可以幫助你避免這個錯誤。

+0

+1閱讀凱爾成功的心態 – Simon

+0

+2閱讀凱爾成功的心態 – Ivan

1

讓我們這個例子:

class Foo: 
    def bar(self): 
    print 'bar' 
    @classmethod 
    def baz(cls): 
    print 'baz' 
    @staticmethod 
    def qux(): 
    print 'qux' 

def quux(): 
    print 'quux' 
Foo.quux = quux # note: Foo.quux is a function attribute NOT a method 

然後你就可以有不同的成功措施,這取決於你如何調用這些:

f = Foo() 
f.bar() # works 
getattr(f, 'bar')() # works 
getattr(Foo, 'bar')() # TypeError 
getattr(Foo, 'bar')(f) # works 
f.baz() # works 
getattr(f, 'baz')() # works 
getattr(Foo, 'baz')() # works 

等。遊戲中的基本思想是,當調用方法時,使用語法obj.method(...),該對象本身作爲第一個參數self傳遞;但是當相同的可調用作爲類的一個屬性被尋址時,那麼這個特殊的替換就沒有完成。這也適用於getattr功能。