Search code examples
pythonpython-3.xmultiple-inheritance

Is Multiple Inheritance problematic in Python?


Hello i was searching about class inheritance in python and i saw that it supports Multiple Inheritance as well but somehow seems problematic :o I ve found an example:

class ParentOne:
    def __init__(self):
        print "Parent One says: Hello my child!"
        self.i = 1

    def methodOne(self):
        print self.i

class ParentTwo:
    def __init__(self):
        print "Parent Two says: Hello my child"

class Child(ParentOne, ParentTwo):
    def __init__(self):
        print "Child Says: hello"
A=Child()

Output

Child Says: hello

So when child inherits ParentOne and ParentTwo why arent those classes initialised? Should we manually initialize them within the inherit class Child? Whats the correct example so we can see all messages printed using only inheritage?

In fact, it is slightly more complex than that; the method resolution order changes dynamically to support cooperative calls to super(). This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages.

How can it be more powerful when it need to be initialized manually? Sorry for all these questions. Thanks in advance.


Solution

  • This is what super is for:

    class ParentOne():
        def __init__(self):
            super().__init__()        
            print("Parent One says: Hello my child!")
            self.i = 1
    
        def methodOne(self):
            print(self.i)
    
    class ParentTwo():
        def __init__(self):
            super().__init__() 
            print("Parent Two says: Hello my child")
    
    class Child(ParentOne, ParentTwo):
        def __init__(self):
            super().__init__()
            print("Child Says: hello")
    
    A=Child()
    

    prints

    Parent Two says: Hello my child
    Parent One says: Hello my child!
    Child Says: hello