[Tutor] Using super() in classes

Alan Gauld alan.gauld at yahoo.co.uk
Fri Nov 26 11:52:37 EST 2021


On 26/11/2021 16:06, Manprit Singh wrote:

> class ABC:
>     def show(self):
>         print("HELLO")
> 
> class ABCD(ABC):
>     def show(self):
>         print("HI")
>         super().show()
> 
> obj = ABCD()
> obj.show()

> Just need to know if my explanation is correct or not .

Yes, all good so far.

> given example can be written in the below written way or not ? Here instead
> of writing super().show() in class ABCD i have written ABC.show(self) .According
> to me it will serve the same purpose as that of the above written classes.
> 
> Am I correct ?

In the case of single inheritance 9ie only one superclass) yes.
And that is how most Python code prior to v3 was written. And
for single inheritance, often still is.

But for multiple inheritance super() may behave differently, especially
when you have inheritance "diamonds" at work. eg

class A; pass
class B(A): pass
class C(A): pass
class D(B,C) : pass

Now in the init of D you have the choice of calling B.init, C.init,
super().init.

And since both B and C inherit from A how often should A.init
be called and when?

super is designed to resolve those issues.

As an experiment try it with print() methods as you did above
to show which class is which. See if you find a difference.

The other case to consider is what happens if only one of B or C
implements a method that is implemented by A.
Now you decide override that method in D.
How do you get all 3 methods called?

What if you have multiple levels of inheritance - 3 or 4 deep say?

It all starts to get very complicated if you need to track back
to find which superclass gets called for which method.

> 
> class ABCD(ABC):
>     def show(self):
>         print("HI")
> 
>     def greeting(self, Name):
>         super().show()
>         print(Name)

Not only OK but the preferred way to do it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list