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" , "abc@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)
OutputThe ID is: 103
The Name is: Suraj kr gupta
The Address is: Noida
The Emails is: abc@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.
Python
# 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.
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(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'>]
Similar Reads
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python class
In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
3 min read
Encapsulation and Access Modifiers
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python super()
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 PythonSyntax: super() Return : R
8 min read
Multiple Inheritance in Python
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Special Methods and Testing