The Wayback Machine - https://web.archive.org/web/20241006140740/https://www.geeksforgeeks.org/python-super/
Open In App

Python super()

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.

Syntax of super() in Python

Syntax: super()

Return : Return a proxy object which represents the parent’s class.

super() function in Python Example

In the given example, The Emp class has an __init__ method that initializes the id, and name and Adds attributes. The Freelance class inherits from the Emp class and adds an additional attribute called Emails. It calls the parent class’s __init__ method super() to initialize the inherited attribute.

Python
class Emp():
    def __init__(self, id, name, Add):
        self.id = id
        self.name = name
        self.Add = Add

# Class freelancer inherits EMP
class Freelance(Emp):
    def __init__(self, id, name, Add, Emails):
        super().__init__(id, name, Add)
        self.Emails = Emails

Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")
print('The ID is:', Emp_1.id)
print('The Name is:', Emp_1.name)
print('The Address is:', Emp_1.Add)
print('The Emails is:', Emp_1.Emails)

Output :

The ID is: 103
The Name is: Suraj kr gupta
The Address is: Noida
The Emails is: KKK@gmails

What is the super () method used for?

A method from a parent class can be called in Python using the super() function. It’s typical practice in object-oriented programming to call the methods of the superclass and enable method overriding and inheritance. Even if the current class has replaced those methods with its own implementation, calling super() allows you to access and use the parent class’s methods. By doing this, you may enhance and modify the parent class’s behavior while still gaining from it.

Benefits of Super Function

  • Need not remember or specify the parent class name to access its methods. This function can be used both in single and multiple inheritances.
  • This implements modularity (isolating changes) and code reusability as there is no need to rewrite the entire function.
  • The super function in Python is called dynamically because Python is a dynamic language, unlike other languages.

How does Inheritance work without  Python super?

In the given example, there is an issue with the Emp class’s __init__ method. The Emp class is inherited from the Person class, but in its __init__ method, it is not calling the parent class’s __init__ method to initialize the name and id attributes.

Python
# code
class Person:

    # Constructor
    def __init__(self, name, id):
        self.name = name
        self.id = id

    # To check if this person is an employee
    def Display(self):
        print(self.name, self.id)
    

class Emp(Person):
    
    def __init__(self, name, id):
        self.name_ = name

    def Print(self):
        print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function
Emp_details.name_, Emp_details.name

Output :

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-46ffda859ba6> in <module>
24
25 # calling parent class function
---> 26 Emp_details.name_, Emp_details.name

AttributeError: 'Emp' object has no attribute 'name'

Fixing the above problem with Super in Python

In the provided code, the Emp class is correctly inheriting from the Person class, and the Emp class’s __init__ method is now properly calling the parent class’s __init__ method using super() in Python.

Python
# code
# A Python program to demonstrate inheritance

class Person:

    # Constructor
    def __init__(self, name, id):
        self.name = name
        self.id = id

    # To check if this person is an employee
    def Display(self):
        print(self.name, self.id)
    

class Emp(Person):
    
    def __init__(self, name, id):
        self.name_ = name
        super().__init__(name, id)

    def Print(self):
        print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function
print(Emp_details.name_, Emp_details.name)

Output :

Mayank Mayank

Understanding Python super() with __init__() methods

Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to as a constructor. When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class.

Note: For more information, refer to Inheritance in Python.

Super function with Single Inheritance 

Let’s take the example of animals. Dogs, cats, and cows are part of animals. They also share common characteristics like –  

  • They are mammals.
  • They have a tail and four legs.
  • They are domestic animals.

So, the classes dogs, cats, and horses are a subclass of animal class. This is an example of single inheritance because many subclasses is inherited from a single-parent class.

Python3
# Python program to demonstrate
# super function

class Animals:
    # Initializing constructor
    def __init__(self):
        self.legs = 4
        self.domestic = True
        self.tail = True
        self.mammals = True

    def isMammal(self):
        if self.mammals:
            print("It is a mammal.")

    def isDomestic(self):
        if self.domestic:
            print("It is a domestic animal.")

class Dogs(Animals):
    def __init__(self):
        super().__init__()

    def isMammal(self):
        super().isMammal()

class Horses(Animals):
    def __init__(self):
        super().__init__()

    def hasTailandLegs(self):
        if self.tail and self.legs == 4:
            print("Has legs and tail")

# Driver code
Tom = Dogs()
Tom.isMammal()
Bruno = Horses()
Bruno.hasTailandLegs()

Output :

It is a mammal.
Has legs and tail

Super with Multiple Inheritances

Let’s take another example of a super function, Suppose a class can fly and can swim inherit from a mammal class and these classes are inherited by the animal class. So the animal class inherits from the multiple base classes. Let’s see the use of Python super with arguments in this case.

Python3
class Mammal():

    def __init__(self, name):
        print(name, "Is a mammal")

class canFly(Mammal):

    def __init__(self, canFly_name):
        print(canFly_name, "cannot fly")

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

class canSwim(Mammal):

    def __init__(self, canSwim_name):

        print(canSwim_name, "cannot swim")

        super().__init__(canSwim_name)

class Animal(canFly, canSwim):

    def __init__(self, name):
        super().__init__(name)

# Driver Code
Carol = Animal("Dog")

Output :

The class Animal inherits from two-parent classes – canFly and canSwim. So, the subclass instance Carol can access both of the parent class constructors. 

Dog cannot fly
Dog cannot swim
Dog Is a mammal

Super with Multi-Level Inheritance

Let’s take another example of a super function, suppose a class can swim is inherited by canFly, canFly from the mammal class. So the mammal class inherits from the Multi-Level inheritance. Let’s see the use of Python super with arguments in this case.

Python
class Mammal():

    def __init__(self, name):
        print(name, "Is a mammal")


class canFly(Mammal):

    def __init__(self, canFly_name):
        print(canFly_name, "cannot fly")

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


class canSwim(canFly):

    def __init__(self, canSwim_name):

        print(canSwim_name, "cannot swim")

        super().__init__(canSwim_name)


class Animal(canSwim):

    def __init__(self, name):

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


# Driver Code
Carol = Animal("Dog")

Output :

Dog cannot swim
Dog cannot fly
Dog Is a mammal

Python Multiple Inheritance and MRO

In the given example, class C inherits from classes A and B, and it overrides the age() method. However, in the age() method of class C, the super(C, self).age() line invokes the age() method from the next class in the MRO. In this case, it will invoke the age() method from class A since it appears before class B in the MRO.

Python
class A:
    def age(self):
        print("Age is 21")
class B:
    def age(self):
        print("Age is 23")
class C(A, B):
    def age(self):
        super(C, self).age()
    
c = C()
print(C.__mro__)
print(C.mro())

Output :

(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]

Python super() – FAQs

What is super() in Python?

super() in Python is a built-in function that returns a proxy object (temporary object of the superclass) that allows you to access methods of a base class from a derived class. This is particularly useful in multiple inheritance, as it allows you to avoid explicitly naming the base class.

Why Do I Need super() in Python?

Using super() helps to avoid explicitly referring to the base classes by name and ensures that the correct methods are called in the presence of multiple inheritance. It is useful for accessing overridden methods, avoiding the duplication of code, and providing a hook into cooperative multiple inheritance.

What is super().__init__()?

super().__init__() is used to call the __init__() method of the superclass in a derived class. This is necessary when you want to ensure that the initialization code in the base class is executed before executing any in the derived class.

Example:

class Base:
def __init__(self):
print("Base initializer")

class Child(Base):
def __init__(self):
super().__init__() # Calls the Base class __init__()
print("Child initializer")

obj = Child() # Output: Base initializer
# Child initializer

Is super() Automatically Called?

No, super() is not automatically called in Python. You need to explicitly call it when you want the superclass’s implementation of a method to be executed. This is particularly true for constructors or any overridden methods.

What is the Difference Between super() and super?

  • super(): This is the function call that returns a proxy object to the superclass, allowing you to call its methods.
  • super: This is the actual built-in function or type itself. Without the parentheses and subsequent method call, it’s just a reference to the function and does nothing on its own.


Previous Article
Next Article

Similar Reads

OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
Python | super() in single inheritance
Prerequisites: Inheritance, function overriding At a fairly abstract level, super() provides the access to those methods of the super-class (parent class) which have been overridden in a sub-class (child class) that inherits from it. Consider the code example given below, here we have a class named Square and an another class named Cube which inher
6 min read
Calling a Super Class Constructor in Python
Classes are like creating a blueprint for an object. If we want to build a building then we must have the blueprint for that, like how many rooms will be there, its dimensions and many more, so here the actual building is an object and blueprint of the building is a class. A Class is a user-defined data-type which has data members and member functi
4 min read
Python Multiple Inheritance With super() Function
We are given some classes and our task is to find out how super() function works with multiple inheritance in Python. In this article, we will see how Python super() works with Multiple Inheritance. Python Multiple Inheritance With super() Below, are examples of how Python's Super() Work with Multiple Inheritance in Python: Example 1: Multiple Inhe
2 min read
Python | super() function with multilevel inheritance
super() function in Python: Python super function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'. To understand Python super function we must know about the inheritance. In Python inherita
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
Python Foreach: How to Program in Python
In many programming languages, the foreach loop is a convenient way to iterate over elements in a collection, such as an array or list. Python, however, does not have a dedicated foreach loop like some other languages (e.g., PHP or JavaScript). In this article, we will explore different ways to implement a foreach-like loop in Python, along with ex
3 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage & store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Practice Tags :