Frage

When deriving from a builtin type as well as from some other class, it seems that the builtin type's constructor doesn't call the super class constructor. This results in __init__ methods not being called for types that come after the builtin in the MRO.

Example:

class A:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print("A().__init__()")

class B(list, A):
    def __init__(self, *args, **kwargs):
        print("B().__init__() start")
        super().__init__(*args, **kwargs)
        print("B().__init__() end")

if __name__ == '__main__':
    b = B()

In this sample, A.__init__ is never called. When B is defined as class B(A, list) instead -- switching the inheritance order -- it works as intended (i.e. A.__init__ is called).

This very subtle dependence on inheritance order seems rather un-pythonic, is it intended this way? It also means that you must never derive from builtin types in complex class hierarchies, because you can't know where the builtin ends up in the MRO when someone else derives from your classes (maintenance horror). Am I missing something?

Extra info: Python version 3.1

Keine korrekte Lösung

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top