One of the most widely used and one of the most misunderstood is init in python. Python is one of the object-oriented paradigm (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 is object-oriented programming 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.
Contents of Tutorial
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.
In object-oriented programming, a class is a collection of related elements with the same or different data types. Like, if we have a Student class, the variables would be named, age, section, gender, etc. And the operations that can be performed by the objects are calculate_marks().
An object is the run time entity of a class and used to perform operations, declared in the class. It contains the state and behavior of the class. For a student class, by the state, it means properties like name, age, roll number, and by the behavior, it means what 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 just like the constructor in other 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. And the best thing is we can also initialize the attributes of the class like name, age, etc. while initializing the object.
class example: # constructor initialized def __init__(self): print("__init__ called")
e=example() # __init__ called
Calling __init__ in python
You must have noticed a parameter named “self” 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 of learning. Now let us understand what this self keyword is?
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 of the programming languages use this type of keyword in the background, but that is not the case with init in python.
Without getting in 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)
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 have made two objects of the Student class, namely 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 like when we print(student1.age), it is printing the age of student1, and if we print(student2.age), it is printing the age of 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 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
Inheritance – __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()
Output- Person Init called. Student Init called. Student Vicky Person Init called. Employee Init called. Employee Vikas
Note that, here the Person class’s constructor has been called first. This happens in most of the 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()
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()
Notice that we have to write lesser code if we use super(). Even it was a small piece of code using super(), we managed to reduce the number of lines, imagine if had multiple classes dependent on one class, how smaller our code would have gotten using super().
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python in 2020
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.