“Super” in python: why and when to use

One of the primary OOPS concept that dominates python is Inheritance. Super is useful for accessing inherited methods that have been overridden in a class.

For more theory details, refer Python’s official doc on Super.

Lets start with practical example:

class A(object):
	print ("I am in class A")

class B(A):
	print ("I am in class B")

B_obj=B()

In the above code we have defined two classes A and B. As you see above, class B inherits properties of A.
The output of above code is:

I am in class A
I am in class B

Now let us modify our above code to little bit more complex.

class A(object):
	def func(self):
		print ("I am in class A")

class B(A):
	def __init__(self):
		print ("I am in class B")

B_obj=B()

The output is as follows:

I am in class B

Now say, I want to execute func method of class A before executing __init__ of class B. How do I do it? This is where super comes into action.

class A(object):
	def func(self):
		print ("I am in class A")

class B(A):
	def __init__(self):
		super().func()
		print ("I am in class B")

B_obj=B()

The output of above code is:

I am in class A
I am in class B

Similarly, we can use super to call same method in different classes. Say classA has __init__ and classB also has __init__ defined (B inherits A), when we create the instance of classB, only __init__ of classB is executed. Here if we want __init__ of classA to be executed before __init__ of classB, then we can use super.

Now you know when and how to use super of python. If you have any queries, feel free to ask by commenting in this post.

One thought on ““Super” in python: why and when to use”

Leave a Reply

Your email address will not be published. Required fields are marked *