Open In App

__init__ in Python

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

__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

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

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

Python3




# 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: 

Python3




# 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

We have covered __init__ in Python, discussed how to use __init__, and also saw some examples of using __init__ method in Python.

Constructor is a crucial concept in OOPs, and __init__ method is very similar to constructors.

Hope this article helped you in learning __init__ method, and you will be able to use it in your projects.

Related Article



Similar Reads

Is __init__() a private method in Python?
Here in this article we are going to find out whether __init__() in Python is actually private or not. So we might come across many questions like What actually is __init__() method?What actually are private methods?And, if __init__() is private then how can we access it outside of a class? We have already heard about the concept that private metho
3 min read
Python Super() With __Init__() Method
In object-oriented programming, inheritance plays a crucial role in creating a hierarchy of classes. Python, being an object-oriented language, provides a built-in function called super() that allows a child class to refer to its parent class. When it comes to initializing instances of classes, the __init__() method is often used. Combining super()
4 min read
What Does Super().__Init__(*Args, **Kwargs) Do in Python?
In Python, super().__init__(*args, **kwargs) is like asking the parent class to set itself up before adding specific details in the child class. It ensures that when creating an object of the child class, both the parent and child class attributes are initialized correctly. It's a way of saying, In this article, we will see about super().__init__()
4 min read
What is __Init__.Py File in Python?
One of the features of Python is that it allows users to organize their code into modules and packages, which are collections of modules. The __init__.py file is a Python file that is executed when a package is imported. In this article, we will see what is __init__.py file in Python and how it is used in Python. What Is __Init__.Py File in Python?
5 min read
What is the difference between __init__ and __call__?
Dunder or magic methods in Python are the methods having two prefixes and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. In this article, we are going to see the difference between t
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Article Tags :
Practice Tags :