Python MRO and super() Isn't Behaving as Expected

26 views Asked by At

With the following code below, the expected output of

Bottom2().method()

would be

Bottom2
Top

However, "Top" is missing. Why?

Reference: Super Python (part 2)

>>> import platform
>>> platform.python_version()
'3.10.7'
>>> class Top:
...     def method(self):
...         print('Top')
...
>>>
>>> class Left(Top):
...     def method(self):
...         print('Left')
...         super().method()
...
>>> class Right(Top):
...     def method(self):
...         print('Right')
...         super().method()
...
>>> class Bottom(Left, Right):
...     def method(self):
...         print('Bottom')
...         super(Left, self).method()
...
>>> class Bottom2(Left, Right):
...     def method(self):
...         print('Bottom2')
...         super(Right, self).method
...
>>> Bottom().method()
Bottom
Right
Top
>>>
>>> Bottom.mro()
[<class '__main__.Bottom'>, <class '__main__.Left'>, <class '__main__.Right'>, <class '__main__.Top'>, <class 'object'>]
>>> Bottom2().method()
Bottom2
>>> Bottom2.mro()
[<class '__main__.Bottom2'>, <class '__main__.Left'>, <class '__main__.Right'>, <class '__main__.Top'>, <class 'object'>]
1

There are 1 answers

0
Thomas On

See @Daraan's question. I forgot the () after .method. Added them and now the code works as expected.

class Bottom2(Left, Right):
    def method(self):
        print('Bottom2')
        super(Right, self).method # <========

>>> class Bottom2(Left, Right):
...     def method(self):
...         print('Bottom2')
...         super(Right, self).method()
...
>>> Bottom2().method()
Bottom2
Top
>>>