Example of __init__ method in Python

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

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)
 
 
# Creating different objects
p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')
 
p1.say_hi()
p2.say_hi()
p3.say_hi()


Output:

Hello, my name is Nikhil
Hello, my name is Abhinav
Hello, my name is Anshul

__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....