What Is The __Init__ In Python?

What Is The __Init__ In Python?

Published on September 28 2023

In this tutorial, we will learn Python's __init__ method. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • __init__ is a method or constructor in Python.
  • All classes have the __init__ method.
  • The __init__ method is called automatically whenever a new object/ instance of a class is created.
  • This method allocates memory to the new object as soon as it is created.
  • This method can also be used to initialize variables.
  • If you have multiple constructors defined in Python, python always calls the last defined constructor.

Sample Code

# class definition 
class Employee:
    # Constructor 
    def __init__(self, name, age):
        self.name = name
        self.age = age 
        
    # creating a new object of class 
    Employee emp1 = Employee("Jack", 23) 
    #__init__ allocates memory for emp1 object. 
    print(emp1.name)
    print(emp1.age)

Multiple Constructor

# class definition 
class Employee: 
    # Constructor 
    def __init__(self): 
        print('A') 
        
    def __init__(self): 
        print('B') 
        
    def __init__(self): 
        print('C') 
            
    # creating a new object of class 
    Employee emp1 = Employee()

Multiple Constructor Output

C   # Output

To know about it, please refer to the official documentation website - official website.