Home > OS >  Python Multiple Inheritance super().__init__()
Python Multiple Inheritance super().__init__()

Time:08-27

I have two classes, with the same parameter initialized by their __init__ method. I would like to inherit both classes in class "X". But I will get: TypeError: B.__init__() missing 1 required positional argument: 'my_param'

Reproducible Example:

class Abstract: ...


class A:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param


class B:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param * 2


class X(A, B):
    def __init__(self, my_param):
        super().__init__(my_param=my_param)

a = X(my_param=1)
print(a.my_param)

Is there a way to set my_param for each of A and B or to set it without getting the error?

CodePudding user response:

Change A and B to pass the parameter when they call super().__init__().

class A:
    def __init__(self, my_param):
        super().__init__(my_param=my_param)
        self.my_param = my_param


class B:
    def __init__(self, my_param):
        super().__init__(my_param=my_param)
        self.my_param = my_param * 2

CodePudding user response:

Since A and B share the same fields, I think it makes sense to make one inherit from the other - in this case, B inherit from A. That way, you'll only need to subclass from B in class X.

For example:

class A:
    def __init__(self, my_param):
        self.my_param = my_param


class B(A):
    def __init__(self, my_param):
        super().__init__(my_param * 2)
        # or:
        #   A.__init__(self, my_param * 2)


class X(B):
    def __init__(self, my_param):
        super().__init__(my_param=my_param)


a = X(my_param=1)
print(a.my_param)  # 2
  • Related