Python的类型错误:__init __()到底需要3个参数(4给出)
问题描述:
我有下面的类和功能在我的程序: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)
答
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)
你可以把这两行成一个功能或许,然后调用代替。
您的异常和发布的代码不匹配。你是否已经纠正了错误,但忘了重启Python解释器? –
@Martijn彼得斯,但自我的RaiseAndTurnOff是不同于我从功能 – Sarit8
发送的自我是的,这的确是不同的。你现在想做什么,为什么你想要通过一个不同的'自我'?你不能这样做*和*同时创建一个'RaiseAndTurnOff'的实例。 –