Python-TypeError:__ init __()需要3个参数(给定4个)

时间:2016-04-21 12:16:57

标签: python exception

我的程序中有以下类和函数:

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 个答案:

答案 0 :(得分: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)

您可能希望将该长字符串分解为chucks以获得可读性:

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)

你可以将这两行放入一个函数中,然后再调用它。