Python Super() With __Init__() Method
Last Updated :
26 Feb, 2024
In object-oriented programming, inheritance plays a crucial role in creating a hierarchy of classes. Python, being an object-oriented language, provides a built-in function called super()
that allows a child class to refer to its parent class. When it comes to initializing instances of classes, the __init__()
method is often used. Combining super()
with __init__()
can be particularly useful when you want to extend the behavior of the parent class's constructor while maintaining its functionality.
What is super()
With __init__()
Methods?
The super()
function in Python is used to refer to the parent class. When used in conjunction with the __init__()
method, it allows the child class to invoke the constructor of its parent class. This is especially useful when you want to add functionality to the child class's constructor without completely overriding the parent class's constructor.
Syntax:
class ChildClass(ParentClass):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Child class specific initialization code
Here, super().__init__(*args, **kwargs)
calls the __init__()
method of the parent class with the arguments and keyword arguments passed to the child class's constructor.
Python Super() With __Init__() Methods Example
Below, are the example of Python Super() With __Init__() Methods in Python:
Example 1: Basic Inheritance
In this example, below Python code defines two classes, `Animal` and `Dog`, with the `Dog` class inheriting from `Animal`. The `__init__` method in each class initializes attributes (`name` in `Animal` and `name` and `breed` in `Dog`). An instance of the `Dog` class named "Buddy" with the breed "Labrador" is created, and its attributes are printed, displaying the dog's name and breed.
Python3
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
# Creating an instance of the Dog class
my_dog = Dog("Buddy", "Labrador")
print(f"My dog's name is {my_dog.name} and it's a {my_dog.breed}.")
OutputMy dog's name is Buddy and it's a Labrador.
Example 2: Multiple Inheritance
In this example, below Python code defines three classes, `A`, `B`, and `C`. Class `C` inherits from both `A` and `B`. In the `__init__` method of class `C`, `super().__init__(a)` is used to call the constructor of class `A` with the parameter `a`, and `B.__init__(self, b)` is used to call the constructor of class `B` with the parameter `b`. An instance of class `C` named `my_instance` is created with specific attributes for each class.
Python3
class A:
def __init__(self, a):
self.a = a
class B:
def __init__(self, b):
self.b = b
class C(A, B):
def __init__(self, a, b, c):
super().__init__(a)
B.__init__(self, b)
self.c = c
# Creating an instance of the C class
my_instance = C("A_attr", "B_attr", "C_attr")
print(f"A: {my_instance.a}, B: {my_instance.b}, C: {my_instance.c}")
OutputA: A_attr, B: B_attr, C: C_attr
Example 3: Diamond Inheritance
In this example, this Python code demonstrates multiple inheritance with classes A
, B
, C
, and D
. Classes B
and C
inherit from class A
, and class D
inherits from both B
and C
. The __init__
methods of classes B
, C
, and D
utilize super().__init__()
to ensure that the initialization of class A
is called only once. When an instance of class D
is created ( my_instance = D()
).
Python3
class A:
def __init__(self):
print("Initializing class A")
class B(A):
def __init__(self):
super().__init__()
print("Initializing class B")
class C(A):
def __init__(self):
super().__init__()
print("Initializing class C")
class D(B, C):
def __init__(self):
super().__init__()
# Creating an instance of the D class
my_instance = D()
OutputInitializing class A
Initializing class C
Initializing class B
Conclusion
The use of super()
with __init__()
methods in Python provides a powerful mechanism for managing class hierarchies and ensuring that the initialization of attributes is done in a consistent and organized manner. It allows child classes to extend the behavior of their parent classes while maintaining a clear and readable code structure. Understanding and utilizing super()
with __init__()
methods is a key aspect of effective object-oriented programming in Python.
Similar Reads
What Does Super().__Init__(*Args, **Kwargs) Do in Python?
In Python, super().__init__(*args, **kwargs) is like asking the parent class to set itself up before adding specific details in the child class. It ensures that when creating an object of the child class, both the parent and child class attributes are initialized correctly. It's a way of saying, In
4 min read
tuple() Constructor in Python
In Python, the tuple() constructor is a built-in function that is used to create tuple objects. A tuple is similar to a list, but it is immutable (elements can not be changed after creating tuples). You can use the tuple() constructor to create an empty tuple, or convert an iterable (such as a list,
2 min read
Initialize Python Dictionary with Keys and Values
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize
3 min read
Declare variable without value - Python
A variable is a container that stores a special data type. Unlike C/C++ or Java, a Python variable is assigned a value as soon as it is created, which means there is no need to declare the variable first and then later assign a value to it. This article will explore How to Declare a variable without
2 min read
How to Initialize a String in Python
In Python, initializing a string variable is straightforward and can be done in several ways. Strings in Python are immutable sequences of characters enclosed in either single quotes, double quotes or triple quotes. Letâs explore how to efficiently initialize string variables.Using Single or Double
2 min read
What is __Init__.Py File in Python?
One of the features of Python is that it allows users to organize their code into modules and packages, which are collections of modules. The __init__.py file is a Python file that is executed when a package is imported. In this article, we will see what is __init__.py file in Python and how it is u
5 min read
How to Call a Method on a Class Without Instantiating it in Python?
In Python programming, classes and methods are like building blocks for organizing our code and making it efficient. Usually, we create instances of classes to access their partsâattributes and methods. But sometimes, we might want to use a class or its methods without actually creating an instance.
3 min read
Python Runtimeerror: Super() No Arguments
Python, a versatile programming language, provides developers with a powerful toolset for creating complex applications. However, like any programming language, it comes with its share of challenges. One such issue that developers might encounter is the "RuntimeError: super(): no arguments." This er
4 min read
Python | Use of __slots__
When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space. slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisa
2 min read
How To Make a Subclass from a Super Class In Python
In Python, you can create a subclass from a superclass using the class keyword, and by specifying the superclass in parentheses after the subclass name. The subclass inherits attributes and behaviors from the superclass, allowing you to extend or modify its functionality while reusing the existing c
3 min read