Search code examples
pythoninheritanceinitialization

Python child class initialiser argument


I have a parent class whose initialiser has three argument, now I want to have a child class whose initialiser only has two argument, but it's telling me it has to be given three arguments when I try to create the child object.

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")

What I'm trying to do is instantiate a Child object with only one argument then in the initialiser of that Child object call Parent's initialiser and pass in two argument, one is hard-coded (123) .

Error I got: TypeError: __init__() takes exactly 3 arguments (2 given)


Solution

  • you should be able to use:

    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)