2014-01-27 30 views
0

當我試圖從我的類調用我的函數時,會引發此錯誤。 這是我的課:unbound方法MyFunction()必須用作爲第一個參數的Tools實例調用(沒有任何代替)

class Tools: 
    def PrintException(self): 
     # Do something 
     return 'ok' 

View.py:

from tools import Tools 

def err(request): 
    a = 10 
    b = 0 
    msg = "" 
    try: 
     print a/b 
    except Exception,ex: 
     c = Tools 
    return HttpResponse(Tools.PrintException()) 

我試圖尋找和發現這個錯誤的許多文章,但我覺得他們都不是我的問題!
unbound method must be called with instance as first argument (got nothing instead)
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

回答

3

什麼分配給c是一類,而不是一個類的實例。你應該這樣做:

c = Tools() 

此外,你應該調用該方法的實例:

def err(request): 
    a = 10 
    b = 0 
    msg = "" 
    try: 
     print a/b 
    except Exception,ex: 
     c = Tools() 
     return HttpResponse(c.PrintException()) 

注意,所以return聲明僅在例外執行的我已經改變了縮進。這是我能想到的唯一方法,以便從中得出一些結論 - 目前還不清楚你想要完成什麼課程。這個名字太通用了 - 它沒有說明這個課程的目的。

2

要使用你的方法沒有一個類的實例就可以把一個類的方法裝飾,像這樣:

class Tool: 
    @classmethod 
    def PrintException(cls): 
     return 'ok' 

可用於:

>>> Tool.PrintException() 
'ok' 
>>> 
相關問題