Search code examples
pythonpython-3.xmultiple-inheritance

Multiple inheritance with multiple parents


Base is superclass.
It has instance variable= sides.
It has show() method which gives value of sides.

Circle inherits Base.
It has show() method which prints classname.

Triangle inherits Base.
It has show() method which prints classname.

Square inherits Base.
It has show() method which prints classname.

Shape inherits Circle,Triangle,Square.
It has show() method which prints "i'm in shape"

We have to create an instance of the Shape class and access the show() method of Circle class using the instance created.

I want to access the show() method of Circle only and not the show() method of the Shape class.

How do I do that?

class Base:
    def __init__(self,sides):
        self.sides=sides

    def show(self):
        return self.sides

class Triangle(Base):
    def show(self):
        print("Triangle")

class Square(Base):
    def show(self):
        print("Square")

class Circle(Base):
    def show(self):
        print("Circle")

class Shape(Circle,Square,Triangle):
    def __init__(self):
        super(Shape,self).show()
    def show(self):
        print("i am in shape")

a=Shape()
a.show()

I was trying to get the output as:

Circle

But the code is giving me the output as:

Circle
i am in shape

how does the code change if i have to call show method of Circle class by a.show() by using the instance of Shape class?


Solution

  • You should leave the super(Shape,self).show() as it is and just instantiate the Shape, which will print Circle as below. The exta a.show() you are calling is printing the extra i am in shape

    class Shape(Circle,Square,Triangle):
    
        def __init__(self):
            super(Shape,self).show()
    
        def show(self):
            print("i am in shape")
    
    #The constructor is called
    a=Shape()
    #Circle
    
    #The show function of class Shape is called
    a.show()
    #i am in shape
    

    If you want to explicitly access the show method of Circle, you need to instantiate that object.

    a=Circle(2)
    a.show()
    #Circle
    

    In addition, look at: How does Python's super() work with multiple inheritance? for more info on how super works for multiple inheritance