__Init__ constructor method in Python

"__init__" &reserved method in Python classes. It is known as a constructor in OOP concepts. This method is called when an object is instantiated from the class, and it allows the class to initialize the class attributes.

How can we use & # 171; __ init __ & # 187 ;?

The purpose of the Python class constructor function &initialize an instance of the class.

Python __init __ () function syntax

 def __init __ (self, [arguments]) 
  • The def keyword is used to define it because it is a function.
  • < li> The first argument refers to the current object. It binds the instance to the init () method. He is usually called "me" to follow the naming convention. You can read more about this in your own Python variable.
  • Arguments to init () are optional. We can define a constructor with any number of arguments.

Let`s see that we are creating a class named Car. A car can have attributes such as "color", "model", "speed", etc., as well as methods such as "start", "accelerate", "shift gears", etc.

 class Car (object): def __init __ (self, model, color, speed): self.color = col or self.speed = speed self. model = model def start (self): print ("started") def accelerate (self): print ("accelerating ...") def change_gear (self, gear_type): print ("gear changed") 
< p> So we used the constructor __init__ method to initialize the class attributes.


Let`s see some examples of constructor function in different scenarios.

1. A class without a constructor

We can create a class without defining a constructor. In this case, the superclass constructor is called to initialize an instance of the class. Class object &it is the basis of all classes in Python.

 class Data: pass d = Data () print (type (d)) # & lt; class `__main__ .Data` & gt; 

Here`s another example to prove that the superclass constructor is called to initialize the subclass instance.

 class BaseData: def __init __ ( self, i): print (f`BaseData Constructor with argument {i} `) self.id = i class Data (BaseData): pass d = Data (10) print (type (d)) 


 BaseData Constructor with argument 10 & lt; class `__main __. Data` & gt; 

2. Simple constructor with no arguments

We can create a constructor with no arguments. This is useful for logging purposes such as counting instances of a class. 

 class Data1: count = 0 def __init __ (self): print (`Data1 Constructor`) Data1.count + = 1 d1 = Data1 () d2 = Data1 () print ("Data1 Object Count =", Data1.count) 


 Data1 Constructor Data1 Constructor Data1 Object Count = 2 

3. Class constructor with arguments

In most cases you will find a constructor function with some arguments. These arguments are typically used to initialize instance variables.

 class Data2: def __init __ (self, i, n): print (`Data2 Constructor`) self.id = i self.name = n d2 = Data2 (10, `Secret`) print (f`Data ID is {d2.id} and Name is {d2.name}`) 

Exit :

 Data2 Constructor Data ID is 10 and Name is Secret 

4. Inherited class constructor

 class Person: def __init __ (self, n): print (`Person Constructor`) self.name = n class Employee (Person): def __init __ (self, i, n): print (`Employee Constructor`) super () .__ init __ (n) # same as Person .__ init __ (self, n) self.id = i emp = Employee (99 , `Pankaj`) print (f`Employee ID is {emp.id} and Name is {emp.name}`) 


 Employee Constructor Person Constructor Employee ID is 99 and Name is Pankaj 
  • We must call the superclass constructor.
  • We can use the super () function to call the superclass constructor function.
  • We can also use the superclass name to call its init () method.

5. Multilevel inheritance constructor chaining

 class A: def __init __ (self, a): print (`A Constructor`) self.var_a = a class B (A): def __init __ (self, a, b): super () .__ init __ (a) print (`B Constructor`) self.var_b = b class C (B): def __init __ (self, a, b, c): super () .__ init __ (a, b) print (`C Constructor`) self.var_c = c c_obj = C (1, 2, 3) print (f`c_obj var_a = {c_obj.var_a}, var_b = {c_obj.var_b}, var_c = {c_obj.var_c} `) 


 A Constructor B Constructor C Constructor c_obj var_a = 1, var_b = 2, var_c = 3 

6. With Multiple Inheritance

We cannot use super () to access all superclasses in case of multiple inheritance. A better approach would be to call the superclass constructor function using their class name.

 class A1: def __init __ (self, a1): print (`A1 Constructor`) sel f.var_a1 = a1 class B1: def __init __ (self, b1): print (`B1 Constructor`) self.var_b1 = b1 class C1 (A1, B1): def __init __ (self, a1, b1, c1 ): print (`C1 Constructor`) A1 .__ init __ (self, a1) B1 .__ init __ (self, b1) self.var_c1 = c1 c_obj = C1 (1, 2, 3) print (f`c_obj var_a = {c_obj. var_a1}, var_b = {c_obj.var_b1}, var_c = {c_obj.var_c1} `) 


 C1 Constructor A1 Constructor B1 Constructor c_obj var_a = 1, var_b = 2, var_c = 3 

Python does not support multiple constructors

Python does not support multiple constructors, unlike other popular object-based oriented programming languages ​​such as Java.

We can define several __init __ () methods, but the last one overrides divides the previous definitions.

 class D: def __init __ (self, x): print (f`Constructor 1 with argument {x} `) # this will overwrite the above constructor definition def __init __ (self, x, y): print (f`Constructor 1 with arguments {x}, {y} `) d1 = D (10, 20) # Constructor 1 with arguments 10, 20 

Can Python`s __init __ () function return something?

If we try to return a non-None value from the __init __ () function, it will raise a TypeError. < / p>

 class Data: def __init __ (self, i): self.id = i return True d = Data (10) 


 TypeError: __init __ () should return None, not `bool` 

If we change the return statement to return None then the code will work without any exceptions.

Get Solution for free from DataCamp guru