Tutorials  /  Python

Python super() & Python 3 super() - Essential Guide

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

Python super() function allows us to refer to the parent class explicitly. It’s useful in case of inheritance where we want to call super class functions.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Python super()

To understand about python super function, you have to know about Python Inheritance. In Python Inheritance, the subclasses inherit from the superclass. Python super() function allows us to refer the superclass implicitly. So, Python super makes our task easier and comfortable. While referring the superclass from the subclass, we don’t need to write the name of superclass explicitly. In the following sections, we will discuss python super function.

Function example

At first, just look at the following code we used in our Python Inheritance tutorial. In that example code, the superclass was Person and the subclass was Student. So the code is shown below.

Python
class Person:
    # initializing the variables
    name = ""
    age = 0

    # defining constructor
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

        # defining class methods

    def show_name(self):
        print(self.name)

    def show_age(self):
        print(self.age)

# definition of subclass starts here
class Student(Person):
    studentId = ""

    def __init__(self, student_name, student_age, student_id):
        Person.__init__(self, student_name, student_age)
        self.studentId = student_id

    def get_id(self):
        return self.studentId  # returns the value of student id

# end of subclass definition

# Create an object of the superclass
person1 = Person("Richard", 23)
# call member methods of the objects
person1.show_age()
# Create an object of the subclass
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()

In the above example, we have called parent class function as:

Code
Person.__init__(self, student_name, student_age)

We can replace this with python super function call as below.

Code
super().__init__(student_name, student_age)

Python 3 super()

Note that the above syntax is for python 3 super function. If you are on python 2.x versions, then it’s slightly different and you will have to do the following changes:

Code
class Person(object):
    ...
    super(Student, self).__init__(student_name, student_age)

The first change is to have object as the base class for Person. It’s required to use the super function in Python 2.x versions. Otherwise, you will get the following error.

Code
Traceback (most recent call last):
  File "super_example.py", line 40, in 
    student1 = Student("Max", 22, "102")
  File "super_example.py", line 25, in __init__
    super(Student, self).__init__(student_name, student_age)
TypeError: must be type, not classobj

The second change in the syntax of the super function itself. As you can see that python 3 super function is a lot easier to use and the syntax is also clean looking.

Multilevel inheritance

As we have stated previously that Python super() function allows us to refer the superclass implicitly. But in the case of multi-level inheritances which class will it refer? Well, Python super() will always refer the immediate superclass. Also Python super() function not only can refer the __init__() function but also can call all other function of the superclass. So, in the following example, we will see that.

Python
class A:
    def __init__(self):
        print('Initializing: class A')

    def sub_method(self, b):
        print('Printing from class A:', b)

class B(A):
    def __init__(self):
        print('Initializing: class B')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class B:', b)
        super().sub_method(b + 1)

class C(B):
    def __init__(self):
        print('Initializing: class C')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class C:', b)
        super().sub_method(b + 1)

if __name__ == '__main__':
    c = C()
    c.sub_method(1)

Let’s see the output of above python 3 super example with multi-level inheritance.

Code
Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3

So, from the output we can clearly see that the __init__() function of class C had been called at first, then class B and after that class A. Similar thing happened by calling sub_method() function.

Why Do We Need the super() Function in Python?

If you have experience with Java, you might know that the base class is accessed using a super object. Python follows a similar concept with the super() function, which allows access to methods and attributes of the parent class.

While it's possible to reference the superclass directly by name in Python, super() becomes especially useful in cases of multi-level inheritance or multiple inheritance. It ensures that the Method Resolution Order (MRO) is correctly followed and prevents redundant method calls in complex inheritance hierarchies.

In summary, super() is a powerful tool that makes inheritance handling in Python more efficient and flexible.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren