1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can one get multiple inheritance working when there are arguments? [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Can somebody explain me, how to handle initializer arguments with python's super() keyword? I am frustrated. There are already many posts discussing __init__ and MRO with the conclusion to always call super().__init__ in every initializer. The examples typically come without any additional arguments. However, super() seems to be completely broken for multiple inheritance as soon as there are arguments to __init__.

    Simple example of multiple inheritance with an (unused) argument:

    class A(object):
    def __init__(self, arg):
    print("A")

    class B(object):
    def __init__(self, arg):
    print("B")

    class C(A,B):
    def __init__(self, arg):
    print("C")
    super().__init__(arg)

    A(1) # -> A
    B(1) # -> B
    C(1) # -> C A (B.__init__ is never called)


    The intuitive way does not work with the way super() is designed:

    class C(A,B):
    def __init__(self, arg):
    print("C")
    super().__init__(arg)
    super().__init__(arg)

    C(1) # -> C A A (A.__init__ is called twice because MRO is reset)


    So, the problem is, that class A does not call super. But:

    class A(object):
    def __init__(self, arg):
    print("A")
    super().__init__(arg)

    A(1) # -> TypeError because it calls object.__init__ with one argument
    C(1) # -> C A B


    so, now I cannot instantiate A anymore. But this fails too:

    class A(object):
    def __init__(self, arg):
    print("A")
    super().__init__()

    C(1) # -> TypeError because it calls B.__init__ without argument


    So the problem is, that the super() call in the simple class A might either go to object (which supports only zero arguments) or to the class B (which requires one argument). The problem arises as soon as there are arguments to the initializers and I see no solution.

    Do you know any solution to this problem? How do you handle super()? It seems to me, that super() should be avoided for any practical example of __init__. It feels unsatisfying to see a flawed language feature and no warnings about using it.

    Continue reading...

Compartilhe esta Página