Search code examples
pythonpython-2.7oopmultiple-inheritance

How to call methods which are present in right side defined class. Python inheritance. multiple inheritance. Dimond scenario python inheritance


I have a class which is inherited from two other classes. When I call the methods from the child class, It always calls the method which mentioned left side in in class definition.

I know this way Python works. It first check the method in left side class and then right side class.

But now I can't change my child class definition. Please get me some help, how can I call same method present in "Second" class.

I am bit new to Python. using python 2.7

class First(object):
    def get_details(self):
        print "This method gets called every time"
        print "I can't change my Child class structure" 

class Second(object):
    def get_details(self):
        print "But I want to call the same method of this class.. "
        print "Please let me know what can I do? How do I call method of second inherited class" 

class Child(First, Second):
    pass


child_obj = Child()
child_obj.get_details()

Solution

  • You can either call it directly:

    Second.get_details(child_obj)
    

    or use .mro() to get the method resolution order and chose the second parent:

    Child.mro()[2].get_details(child_obj)
    

    The method resolution order shows you search order of classes Python uses to find a method:

    >>> Child.mro()
    [__main__.Child, __main__.First, __main__.Second, object]
    

    As soon as it found get_details() in this list it stops and uses it.

    I would suggest to hide this logic in a method of Child:

    class Child(First, Second):
    
        def get_details_second_1(self):
            """Option 1"""
            return Second.get_details(self)
    
        def get_details_second_2(self):
            """Option 2"""
            return Child.mro()[2].get_details(self)
    
    child_obj = Child()
    child_obj.get_details_second_1()
    child_obj.get_details_second_2()