Python super() function explained [Easy Examples]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Related Searches: python super, python super init, super init python, python class super, python super __init__, python super function, super init, python call super, super class python, python super class, python inheritance super, python super method, super function python, python init super, python call super init, class inheritance python super, python subclass init super, super self python, call super init python, python super super, python __init__ super, pytho super, how to use super init python, inheritance python super

Introduction to Python super() function

A Python can do both structured programming and Object-oriented programming as well. The Python super() function is a built-in function used mainly in object-oriented programming. The basic knowledge of OOP is required to understand the purpose and the use of the python super() function. One of the important features of OOP is inheritance, where a new class can be created which takes all the properties from an existing class known as parent class. The python super() function is used in the child class to refer to the parent class and access all the parent class's functions and variables. In this tutorial, we will learn how we can get access to the methods and variables of the parent class using the python super() function inside the child class.

We will discuss about single and multiple inheritances and some more concepts using the python super() function. By the end of this tutorial, you will have a deep knowledge of the python super() function.

Python super() function Syntax

To understand the python super() function, we have to understand and should have some knowledge of python inheritance. The python super() function allows us to refer to the superclass implicitly. It makes the task easier and comfortable. while referring to the superclass/parent class from the subclass/child class, we don't need to write the name of the parent class explicitly.

Here is a simple python syntax for the Python super() function. See the code below:

super().method_name

The python super() function returns an object that represents the parent class.

Advantages of python super() function

Python supper() function has many advantages. Some of which are listed below:

  • We don't need to remember the parent's class name while using the Python super() function. This is because we don't have to specify the name of the parent class to access the methods present in it. The python super() function allows us to refer to the superclass implicitly
  • It makes the task easier and comfortable
  • We can use the python python super() function with the single inheritance and multiple inheritances.
  • The python super() function in Python is a dynamical function.
  • The Python super() function in Python implements code reusability and modularity as there is no need for us to rewrite the whole function again and again.

The advantages are not only limited to the above-mentioned ones.

Examples of Python super() function in a single inheritance

When a child class is created by inheriting a parent class, then it is called single inheritance. In this section, we will look at how we can use the python super() function in single inheritance. For example, let us say we have a parent class named University in the following python program, that contains a construct method to initialize the data. And we have a child class that inherits the properties from the parent class. See the following example of how we used the python super() function to get access to the functionalities of the parent class.

# parent class
class University:

 # constructor
 def __init__(self, Univeristy_name):

   # prints the name of university
   print(Univeristy_name, 'is the name of university.')

# child class
class Faculty(University):

   # constructor
 def __init__(self):

   # prints total faculty
   print('Total faculty numbers is 300.')

   # get access to parent class using python init super function
   super().__init__('UCA')
  

# object type of Faculty
uni = Faculty()

Output:

Total faculty numbers is 300.
UCA is the name of university.

Notice in the above example that, we didn't call the parent class explicitly, In fact, we create object type Faculty and it actually uses superclass to get access to the constructor and prints the name of the university.

Now let us take another example and see how we can access other methods of parent class using python super function without explicitly using its name. See the example below:

# parent class
class University:

   # constructor
 def __init__(self, Univeristy_name):

   # prints the name of university
   print(Univeristy_name, 'is the name of university.')

   # method which returns the location
 def location(self):
     print('It is located in Naryn')

# child class
class Faculty(University):

 # constructor
 def __init__(self):

   # prints total faculty
   print('Total faculty numbers is 300.')

   # get access to parent class using super function
   super().location() 

 # object type of Faculty
uni = Faculty()

Output:

Total faculty numbers is 300.
It is located in Naryn

Notice that in the above example, we get access to the method named location() which is in the parent class by using the python super() function. In a similar way, we can also get access to the variables in the parent class by using the python super() function. See the example below:

# parent class
class University:
#class variables
 Class_rooms = 10
 Faculty_total = 50

   # constructor
 def __init__(self, Univeristy_name):

   # prints the name of university
   print(Univeristy_name, 'is the name of university.')

# child class
class Faculty(University):

 # constructor
 def __init__(self):

   # get access to parent class varibales using super function
   print(super().Class_rooms)
   print(super().Faculty_total) 

 # object type of Faculty
uni = Faculty()

Output:

10
50

The python super() function gets access to the variables and methods of the parent class without explicitly calling it.

Examples of Python super() function in multiple inheritances

We already know that when a new class is generated by inheriting multiple classes, is known as multiple inheritances. In this section, we will learn how we can use the python super() function to get access to multiple parent classes. For example, we have a parent class named University that contains a constructor to initialize the variable and print the name of the University. Then we have a class named Faculty which inherits class university and print the name of Subject. And we have another parent class named Department which prints out the name of the Department. Finally, we have a child class that first inherits all the properties from the above-mentioned two parents' classes and gets access to their methods by using the python super() function.

See the example below:

# parent class
class Univeristy():

   # constructor
   def __init__(self, name):

       # print the name
       print(name, "---> University name")

# Faculty class
class Faculty(Univeristy):

   # constructor
   def __init__(self, Fname):

       # print subject name
       print(Fname, "---->Major subject Python") 

       # Calling Parent class
       # Constructor
       super().__init__(Fname)

# class Department
class Department(Univeristy):

   # constructor
   def __init__(self, Dname):

       # printing department
       print(Dname, " ----->department CS")
       # super function
       super().__init__(Dname)
# child class with multiple inheritance
class Info(Department, Faculty):

   # cpnstructor
   def __init__(self, name):

       # Calling the constructor
       # of both the parent class in the order of their inheritance
       super().__init__(name)

# creating object
info =Info("UCA")

Output:

UCA ----->department CS
UCA ---->Major subject Python
UCA ---> University name

In a similar way, we can get access to other methods and class variables as well using the python super() function in multiple inheritances.

Overriding methods using Python super() function

Overriding is when we define a parent class's method in the child class again. In other words, the child class can override methods of its parent or superclass by defining the function with the same name. But the following rules are applied for overriding

  • The name of the method should be the same and its parameters as well.
  • If the superclass method is private (prefixed with double underscores), then you can’t override it.

In Python, we can use the Python super() method for overriding. It has the following syntax.

super(class_name, self).override_method_name()

Now let us take one example and see how we can override the methods of parent class using the python super() function.  Let way we have the same code, with the parent class of the University which has a method named, main which prints the name of the university, then in the child class we again defined the main class. See the example below:

# parent class
class University:

   # main function
   def main(self):

       # prints name
       print('UCA!')

# child class
class child(University):

   # overrides main method
   def main(self):

       # prints overrided
       print('Method override!!')

       # super method to call the override method from parent class
       super(child, <i>self</i>).main()

# create object
uni = child()

# calling the method
uni.main()

Output:

Method override!!
UCA!

Notice that we override the method main inside the child class, and then using the python super() function, we were able to get access to the method in the parent class.

Method resolution order

The Method Resolution Order (MRO) is the order in which methods should be inherited in the presence of multiple inheritances. we can always view the MRO by using the __mro__ attribute. See the following example.

# parent class one
class University:

   # constructor
 def __init__(self, Univeristy_name):

   # prints the name of university
   print(Univeristy_name, 'is the name of university.')

# child class
class Faculty(University):

   # constructor
 def __init__(self, name):
   print("Major subject is CS")

   # super function
   super().__init__(name) 

 # child class
class Info(Faculty, University):

   # constructor
   def __init__(self):

       # using supper function
       super().__init__("UCA")

# mro
info = Info()
print(info.__mro__)

Output:

(<class '__main__.Info'>, <class '__main__.Faculty'>, <class '__main__.University'>, <class 'object'>)

Notice that the method in the derived calls has always been called before the method of the base class. This is how MRO works.

Summary

The Python super() function can only be used inside the child class to call the constructor and any other parent class method. In this tutorial, we learned about this method and learned the working principle of the python super() function by taking different examples. We covered how we can use the supper() function in single inheritance and multiple inheritances. Moreover, we also come across how to use the python super() function in the python method overriding process. Towards the end, we also covered method resolution order and see how we can print out the order. All in all, this tutorial covers all the information that you need to start working with the python super() function.

Further Reading

Python super function with examples
python super function documentation

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

X