Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Puzzle about super() method

I am trying to understand how the super() method works. Here is the sample code I am using:

class A(object):
    def __init__(self):
        self.n = 'A'

    def func(self):
        print('@A')
        self.n += 'A'


class B(A):
    def __init__(self):
        self.n = 'B'

    def func(self):
        print('@B')
        self.n += 'B'


class C(A):
    def __init__(self):
        self.n = 'C'

    def func(self):
        print('@C')
        super().func()
        self.n += 'C'


class D(C, B):
    def __init__(self):
        self.n = 'D'

    def func(self):
        print('@D')
        super().func()
        self.n += 'D'


print(D.mro())
d = D()
d.func()
print(d.n)

The correct output results are:

[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
DBCD

What I do not understand is why there is no A in the output? I thought when entering Class C, there is a super().func() which calls the func in Class A. However, it is not the case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone help me understand this behavior?

Thank you!

>Solution :

No, each super().func() call lets you call func in the next class in the MRO of self (which may not be the same as the MRO of the current class). When you call C.func on an instance of D, you follow D‘s MRO and see that after C comes B.

B.func doesn’t call super, so the chain ends there, skipping A. If you want B.func to be useable in multiple inheritance situations, it needs to call super().func() too, like the other classes do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading