Last Updated : 12 Jul, 2025
Prerequisites - Python Class and Objects, Self
__init__ method in Python is used to initialize objects of a class. It is also called a constructor. It is like a 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 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.
Python
# 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
# 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__ Method with Inheritance
Inheritance is the capability of one class to derive or inherit the properties from some other class. Let's consider the below example to see how __init__ works in inheritance.
Python
# Python program to
# demonstrate init with
# inheritance
class A(object):
def __init__(self, something):
print("A init called")
self.something = something
class B(A):
def __init__(self, something):
# Calling init of parent class
A.__init__(self, something)
print("B init called")
self.something = something
obj = B("Something")
Output:
A init called B init called
So, the parent class constructor is called first. But in Python, it is not compulsory that the parent class constructor will always be called first.
The order in which the __init__ method is called for a parent or a child class can be modified. This can simply be done by calling the parent class constructor after the body of the child class constructor.
Example:
Python
# Python program to
# demonstrate init with
# inheritance
class A(object):
def __init__(self, something):
print("A init called")
self.something = something
class B(A):
def __init__(self, something):
print("B init called")
self.something = something
# Calling init of parent class
A.__init__(self, something)
obj = B("Something")
Output:
B init called A init called
Read: Inheritance in Python
Related ArticleRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4