init Python | Is __init__ in Python a Constructor?

One of the most widely used and one of the most misunderstood is init in Python. Python is one of the object-oriented paradigms (everything you create is an object), and init in Python terminology is known as a constructor.

Don’t worry if you don’t know what object-oriented programming is or you don’t know about constructors. We will try to explain from the very basics. Now, let us first understand the term Object-Oriented Programming.

Object-Oriented Programming:

Object-oriented programming, commonly referred to as OOPs, is a type of programming language where developers define the data type of data structure and all those operations that we could perform on that data type. One such data type is class.

Class in Python

In object-oriented programming, a class is a collection of related elements with the same or different data types. For example, if we have a Student class, the variables would be named age, section, gender, etc. The operations that can be performed by the objects are calculate_marks().

Object in Python

An object is the run time entity of a class and is used to perform operations declared in the class. It contains the state and behavior of the class. For a student class, the state means properties like name, age, and roll number; by the behavior, it means the type of student he/she is.

Let us now understand the exact concept and use cases of __init__ in Python.

Use of __init__ in Python

__init__ is a special kind of method in Python. It is like the constructor in object-oriented programming languages like C++ and Java.

The property of the constructor is that whenever we initialize an object of a class, the constructor gets automatically called. The best thing is we can also initialize the attributes of the class, like name, age, etc., while initializing the object.

Syntax of __init__ in Python

class example:
    # constructor initialized
    def __init__(self):
        print("__init__ called")
e=example()
# __init__ called

Calling __init__ in python

You must have noticed a ” self ” parameter in the init(). What is the role of the self keyword here? We don’t use it in normal functions. So why are we using it here? If this question comes to your mind, you are on the right path to learning. Now let us understand what this self keyword is.

Self:

The self-keyword is the first parameter of every method of a class and is used to bind the attributes with the given values of the parameters (arguments). Most programming languages use this type of keyword in the background, but that is not the case with init in Python.

Without getting into too many technical terms, let us understand the self-keyword with an example.

class student:
    def __init__(self,name,age):
        self.name=name
        self.age=age 

student1=student("ashwini",20)
student2=student("Sushant",34)
print(student1.name,student1.age)
print(student2.name,student2.age)
__init__ in python
Output-
ashwini 20
Sushant 34

Here, we have created a Student class with three parameters in the init function. The first is self, which we will understand at some time; next is name and age.
Notice that we made two objects of the Student class, student1 and student2. While creating these objects, we have to pass the same number of arguments as in the __init__.

Note that we don’t count the self as a parameter here. In both, the object’s name and age are different. The self-keyword allows every object to have different values. When we print(student1.age), it prints the age of student1, and if we print(student2.age), it prints the age of the 2nd student. If there were no self-keyword, it wouldn’t have been possible.

Different uses of __init__ in Python

We can use the values initialized using init in other functions. Let us look at how.

class student:
  def __init__(self,name,age):
    self.name=name
    self.age=age

class student_marks:
  def __init__(self,name,english,maths,science,sst):
    self.name=name
    self.english=english
    self.maths=maths
    self.science=science
    self.sst=sst

  def calculate_avg_marks(self):
    total_marks=self.english+self.maths+self.science+self.sst
    avg_marks=total_marks/4
    return avg_marks

student1=student_marks("Ashwini",20,12,14,15)
student2=student_marks("Ashu",10,18,16,9)
student3=student_marks("Sonu",16,14,20,11)
student4=student_marks("Sushant",20,20,20,20)

print(student1.calculate_avg_marks())
print(student2.calculate_avg_marks())
print(student3.calculate_avg_marks())
print(student4.calculate_avg_marks())
Output-

15.25
13.25
15.25
20.0
uses of __init__ in Python

Inheritance of __init__ in Python

Inheritance is one of the most important concepts of Object-Oriented Programming. With inheritance, one class can derive or inherit the properties of another class. This helps in reusing the same code so that we do not have to write the same type of code again and again.

class Person():
  def __init__(self,name):
    print("Person Init called.")
    self.name = name

class Student(Person):
  def __init__(self, name):
    Person.__init__(self, name)
    print("Student Init called.")
    self.name = name
  def display(self):
    print("Student",self.name)

class Employee(Person):
  def __init__(self, name):
    Person.__init__(self, name)
    print("Employee Init called.")
    self.name = name
  def display(self):
    print("Employee",self.name)

student = Student('Vicky')
student.display()
employee= Employee('Vikas')
employee.display()
__init__ in python
Output-

Person Init called.
Student Init called.
Student Vicky
Person Init called.
Employee Init called.
Employee Vikas

Note that the Person class’s constructor has been called first here. This happens in most object-oriented programming languages like C++ and Java. But in Python, it depends on the order in which we have called the init function in the sub-class. Let’s see an example.

class Person():
    def __init__(self,name):
        print("Person Init called.")
        self.name = name

class Student(Person):
    def __init__(self, name):
        print("Student Init called.")
        self.name = name
        Person.__init__(self, name)

    def display(self):
        print("Student",self.name)

student = Student('Vicky')
student.display()
__init__ in python
Output-

Student Init called.
Person Init called.
Student Vicky

Super() in python

In Python, if we use super() in the subclass, we can get a temporary object for the superclass, and using it, we can call the methods of the superclass in the subclass.
Let’s take an example to understand it better.

Program to find the area of a cuboid and cube without super()-

class Cuboid:
    def __init__(self, length, width,height):
        self.length = length
        self.width = width
        self.height=height

    def total_surface_area(self):
        return 2*(self.length * self.width +self.width*self.height+self.length*self.height)

class Cube:
    def __init__(self, length):
        self.length = length

    def total_surface_area(self):
        return 6*self.length * self.length
    
cuboid=Cuboid(5,4,3)
print(cuboid.total_surface_area())
cube=Cube(5)
print(cube.total_surface_area())
Output-
94
150


Now let’s use super() to find the same output-

class Cuboid:
    def __init__(self, length, width,height):
        self.length = length
        self.width = width
        self.height=height

    def total_surface_area(self):
        return 2*(self.length * self.width + self.width*self.height+self.length*self.height)

class Cube(Cuboid):
    def __init__(self, length):
        super().__init__(length,length,length)

cuboid=Cuboid(5,4,3)
print(cuboid.total_surface_area())
cube=Cube(5)
cube.total_surface_area()
94
150
Example __init__

Notice that we have to write less code if we use super(). Even if it was a small piece of code using super(), we managed to reduce the number of lines; imagine if we had multiple classes dependent on one class, how smaller our code would have gotten using super().

Must Read:

Conclusion of __init__ in Python

We now know how useful it is __init__ in Python. There are many times when we have to use it. These types of unique methods make Python an excellent programming language.

Try to run the programs on your side, and let me know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments