Search code examples
pythonclassoopinheritancemultiple-inheritance

Python Multiple Inheritance child(parent1, parent2) access parent2 __init__


let's say I have this class

class child(parent1, parent2):
    pass

Would it be possible to access parent2.__init__, if parent1 also has a defined __init__ ?.

Here is my complete code.

class parent1:
    def __init__(self):
        self.color="Blue"

class parent2:
    def __init__(self):
        self.figure="Triangle"

class child(parent1,parent2):
    pass


juan=child()
try:
    print(juan.color)
except Exception as e:
    print(e)
try:
    print(juan.figure)
except Exception as e:
    print(e)

print(juan.__dict__)

I've tried with

class child(parent1,parent2):
    def __init__(self):
        super(parent2).__init__()

but maybe I am missing something?

Thanks. Regards.


Solution

  • parent1 and parent2, if expected to be used in a cooperative multiple inheritance setting, should call super.

    class parent1:
        def __init__(self):
            super().__init__()
            self.color = "Blue"
    
    class parent2:
        def __init__(self):
            super().__init__()
            self.figure = "Triangle"
    

    When you define child, its method resolution order determines which __init__ gets called first, as well as determining which class super() refers to when each time it gets called. In your actual example,

    class child(parent1,parent2):
        pass
    

    parent1.__init__ is called first (since child does not override __init__), and its use of super() refers to parent2. If you had instead defined

    class child2(parent2, parent1):
        pass
    

    then parent2.__init__ would be called first, and its use of super() would refer to parent1.

    super() is used not to ensure that object.__init__ (which doesn't do anything) is called, but rather object.__init__ exists so that it can be called once a chain of super() calls reaches the end. (object.__init__ itself does not use super, as it is guaranteed to be the last class in the method resolution order of any other class.)