Python子类初始化参数

时间:2016-10-12 09:07:31

标签: python inheritance initialization

我有一个父类,其初始化程序有三个参数,现在我想要一个子类,其初始化程序只有两个参数,但它告诉我当我尝试创建它时必须给它三个参数儿童对象。

class Parent(Exception):
    def _init_(self, a, b):
    ...
    super(Parent, self)._init_(a, b)

class Child(Parent):
    def _init_(self, b):
        super(Child, self)._init_(123, b)

# somewhere in the code I have:
raise Child("BAD_INPUT")

我尝试做的是实例化只有一个参数的Child对象,然后在该Child对象的初始化中调用Parent的初始化并传入两个参数,一个是硬编码的(123)

我得到的错误: TypeError: __init__() takes exactly 3 arguments (2 given)

1 个答案:

答案 0 :(得分:1)

你应该可以使用:

class Parent(Exception):
    def __init__(self, a, b):
        self.a = a
        self.b = b

class Child(Parent):
    a = 123
    def __init__(self, b):
        super().__init__(self.a, b)