0

Right, so I have to create this inheritance hierarchy for a school project, so ignoring certain redundancies (like how Square really doesn't need 2 parents), I've come across a strange way Python handles super calls.

When initializing a square in the following code, it calls its super, which executes the Rectangle's initialization method. This makes sense. The rectangle then calls its super, which should go to the Parallelogram's initialization method; however, after some debugging, I've found that when it makes its super call, it is actually calling the Rhombus's initialization method. Can someone explain what is happening here and, if possible, a way to implement this properly without explicitly using class names?

Relevant code is below.

class Parallelogram:
    def __init__(self, base, side, theta):
        self.base = base
        self.side = side
        self.theta = theta

class Rectangle(Parallelogram):
    def __init__(self, base, side):
        super(Rectangle, self).__init__(base, side, 90)

class Rhombus(Parallelogram):
    def __init__(self, side, theta):
        super(Rhombus, self).__init__(side, side, theta)

class Square(Rectangle, Rhombus):
    def __init__(self, side):
        super(Square, self).__init__(side, side)
  • do you know method resolution order – Argus Malware Nov 24 '17 at 22:41
  • 2
    Possible duplicate of [How does Python's super() work with multiple inheritance?](https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – Sandeep Dcunha Nov 24 '17 at 22:41
  • Seeing this is tagged for python-3.x, super() can be done with no arguments. Suggested reading: [Python’s super() considered super!](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) – Matt Eding Nov 26 '17 at 07:51

1 Answers1

0

you can check the execution order of your inheritance through mro of your calling class object

In [257]: Square.__mro__
Out[257]: 
(__main__.Square,
 __main__.Rectangle,
 __main__.Rhombus,
 __main__.Parallelogram,
 object)
Argus Malware
  • 773
  • 7
  • 19
  • Okay, I now understand why this is happening. But what would be the best way to prevent, so that it behaves as expected? Would I have to resort to calling Parallelogram.__init__() explicitly, or is there a way I can still get super() to work? – Kraton9000 Nov 26 '17 at 00:36
  • you have to use super for inheritance and super.function for what you want to achieve ,inthis you want to achieve what is written in init,or you can call any function written in that class – Argus Malware Nov 26 '17 at 04:05