2016-04-21 85 views
-1

我有下面的類和功能在我的程序:Python的類型錯誤:__init __()到底需要3個參數(4給出)

class RaiseAndTurnOff(Exception): 
    def __init__(self, value, r1): 
     self.value = value 
     r1.turn_off_gracefully() 
    def __str__(self): 
     return repr(self.value) 

def assert_state(self, state): 
    if not(self.link.is_in_state(state)): 
     raise RaiseAndTurnOff("Sanity check error: Link should be %s, but it is not! please check the log file reports. Exiting script" % state, self, self.params) 

正如你可以看到我發3個參數。出於某種原因,我得到了以下錯誤:

File "qalib.py", line 103, in assert_state 
    raise RaiseAndTurnOff("Sanity check error: Link should be %s, but it is not! please check the log file reports. Exiting script" % state, self, self.params) 
TypeError: __init__() takes exactly 3 arguments (4 given) 
+1

您的異常和發佈的代碼不匹配。你是否已經糾正了錯誤,但忘了重啓Python解釋器? –

+0

@Martijn彼得斯,但自我的RaiseAndTurnOff是不同於我從功能 – Sarit8

+0

發送的自我是的,這的確是不同的。你現在想做什麼,爲什麼你想要通過一個不同的'自我'?你不能這樣做*和*同時創建一個'RaiseAndTurnOff'的實例。 –

回答

2

Python的結合方法,以實例對你來說,這意味着self參數提供給您。你不需要自己傳遞它。

下降的第一個參數RaiseAndTurnOff

raise RaiseAndTurnOff("Sanity check error: Link should be %s, but it is not! please check the log file reports. Exiting script" % state, self.params) 

你可能想打破長串入吸盤可讀性:

raise RaiseAndTurnOff(
    "Sanity check error: Link should be %s, but it is not! " 
    "please check the log file reports. Exiting script" % state, 
    self.params) 

的Python的邏輯行會自動加入連續字符串文字。

我必須指出,Exception子類的構造函數聽起來像是「關閉」某個東西的錯誤位置。如果可以在沒有副作用的情況下創建異常,那將會好得多;提高例外(將會改名)之前單獨調用self.params.turn_off_gracefully()

self.params.turn_off_gracefully() 
raise SanityException(
    "Sanity check error: Link should be %s, but it is not! " 
    "please check the log file reports. Exiting script" % state) 

你可以把這兩行成一個功能或許,然後調用代替。