What is __init__ in Python?

__init__ method is like default constructor in C++ and Java. Constructors are used to initialize the object’s state.

The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created.

Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It is run as soon as an object of a class is instantiated.

The method is useful to do any initialization you want to do with your object.

Python3




# A Sample class with init method
class Person:
 
    # init method or constructor
    def __init__(self, name):
        self.name = name
 
    # Sample Method
    def say_hi(self):
        print('Hello, my name is', self.name)
 
 
p = Person('Nikhil')
p.say_hi()


Output:

Hello, my name is Nikhil

Understanding the code

In the above example, a person named Nikhil is created. While creating a person, “Nikhil” is passed as an argument, this argument will be passed to the __init__ method to initialize the object.

The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of the Person class can be created by passing different names as arguments.

Below is the example of __init__ in Python with parameters

__init__ in Python

__init__ method in Python is used to initialize objects of a class. It is also called a constructor.

To completely understand the concept of __init__ method, you should be familiar with:

Prerequisites – Python Class and Objects, Self

Similar Reads

What is __init__ in Python?

__init__ method is like default constructor in C++ and Java. Constructors are used to initialize the object’s state....

Example of __init__ method in Python

...

__init__ Method with Inheritance

Let’s look at some examples of __init__ method in Python....