The Wayback Machine - https://web.archive.org/web/20241001210755/https://www.geeksforgeeks.org/__init__-in-python/
Open In App

__init__ in Python

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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

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.

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)


# 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

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

__init__ in Python – FAQs

What is the __init__ Method in Python?

The __init__ method in Python is a special method called a constructor. It is automatically invoked when a new instance (object) of a class is created. The purpose of the __init__ method is to initialize the object’s attributes and perform any other setup necessary when an object is instantiated.

How is __init__ Used in Python Classes?

The __init__ method is defined within a class and typically includes the self parameter, which refers to the instance being created, followed by any other parameters needed to initialize the object.

Example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating an instance of the Person class
person = Person("Alice", 30)
print(person.name) # Output: Alice
print(person.age) # Output: 30

In this example, the __init__ method initializes the name and age attributes of the Person class.

What are Constructors in Python?

Constructors in Python are special methods used to initialize newly created objects. The __init__ method is the constructor in Python. It allows you to set up the initial state of an object by assigning values to its attributes or performing other setup tasks.

How to Initialize a New Object in Python?

To initialize a new object in Python, you create an instance of a class, which automatically invokes the __init__ method.

Example:

class Dog:
def __init__(self, name, breed="Mixed", age=1):
self.name = name
self.breed = breed
self.age = age

# Creating an instance with default parameters
dog1 = Dog("Buddy")
print(dog1.name) # Output: Buddy
print(dog1.breed) # Output: Mixed
print(dog1.age) # Output: 1

# Creating an instance with specified parameters
dog2 = Dog("Max", "Golden Retriever", 5)
print(dog2.name) # Output: Max
print(dog2.breed) # Output: Golden Retriever
print(dog2.age) # Output: 5

What are the Default Parameters in __init__?

The __init__ method can include default parameter values. This allows you to create objects with default attribute values if no arguments are provided for those parameters.

Example:

class Dog:
def __init__(self, name, breed="Mixed", age=1):
self.name = name
self.breed = breed
self.age = age

# Creating an instance with default parameters
dog1 = Dog("Buddy")
print(dog1.name) # Output: Buddy
print(dog1.breed) # Output: Mixed
print(dog1.age) # Output: 1

# Creating an instance with specified parameters
dog2 = Dog("Max", "Golden Retriever", 5)
print(dog2.name) # Output: Max
print(dog2.breed) # Output: Golden Retriever
print(dog2.age) # Output: 5

In this example, the breed and age parameters have default values. If these parameters are not provided when creating a Dog object, the default values will be used.



Previous Article
Next 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
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
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
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
Python Foreach: How to Program in Python
In many programming languages, the foreach loop is a convenient way to iterate over elements in a collection, such as an array or list. Python, however, does not have a dedicated foreach loop like some other languages (e.g., PHP or JavaScript). In this article, we will explore different ways to implement a foreach-like loop in Python, along with ex
3 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage & store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
8 min read
Future of Python : Exploring Python 4.0
The future of Python 4.0 is a topic of great anticipation and speculation within the tech community. Guido van Rossum, the creator of Python, offers exclusive insights into what might lie ahead for this popular programming language. With Python 3.9 approaching its release, many are curious about t the potential for Python 4.0. This article explores
8 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Article Tags :
Practice Tags :