Python Tutorial

Python init Function (Guide to __init__ in Python)

Table of Contents

  • Introduction
  • What is init in Python?
  • Role and Use of init Function in Python?
  • Syntax of init in Python
  • How the __init__ Function is Called Automatically?
  • Role of self Parameter
  • Setting Up Instance Variables in __init__ function
  • Using Default Parameter Values in __init__
  • Using Optional Parameters in __init__
  • __init__ with Inheritance


In Python object-oriented programming, there exists a fundamental element that plays a crucial role in shaping the behavior of classes and their instances—the __init__ function. As a Python developer, you've likely encountered this enigmatic method, but do you truly grasp its significance and potential?

This post is your guide to the init in Python. Whether you're a beginner seeking a solid foundation or an experienced developer looking to enhance your understanding, this exploration will cover everything— from the basics to advanced techniques.

What is init in Python?

The __init__ function in Python is a special method within a class that is automatically called when an object of that class is created. The init in Python stands for "initialize" and is commonly referred to as the initializer or constructor

The primary purpose of the __init__ method is to set up the initial state of an object by defining and initializing its attributes.

These are key aspects of the __init__ function:

  • Initialization: The __init__ method is where you define the attributes (properties or variables) that the objects of the class will have. It's the place to initialize the object's state.

  • Automatic Invocation: When you create an instance of a class using the class name followed by parentheses, e.g., my_instance = MyClass(), Python automatically calls the __init__ method for that instance.

  • self Parameter: The first parameter of the __init__ method is typically self, which refers to the instance being created. It is a convention in Python, and it allows you to access and modify the object's attributes.

Role and Use of init Function in Python?

The __init__ function holds significant importance in Python classes for several reasons:

  • Object Initialization

Setting Initial State: The primary purpose of the __init__ function is to initialize the attributes of an object. This ensures that when an instance of a class is created, it starts with a defined and consistent state.

Default Values: It allows you to provide default values for attributes, making it convenient for users to create instances with a minimum amount of information, and allowing for flexibility in object creation.

  • Automatic Invocation

Implicit Call: The __init__ method is automatically called when an object is created. This automatic invocation ensures that the initialization code is executed at the right time, without the need for explicit calls.

Self-Reference: The self parameter in the __init__ method refers to the instance being created. This self-reference allows you to work with the instance and set its attributes.

  • Attribute Assignment

Defining Attributes: Within the __init__ method, you define the attributes that characterize the object. This encapsulation of attributes helps in organizing and maintaining the state of objects.

Attribute Flexibility: It provides a mechanism to set attributes dynamically based on the arguments passed during object creation. This flexibility enhances the adaptability of your classes.

  • Consistency and Readability

Standardized Initialization: Using the __init__ method promotes a standardized way of initializing objects in a class. This consistency improves code readability and makes it easier for developers to understand how to create instances of the class.

Documentation: The __init__ method serves as a natural place to document and communicate the essential attributes of a class, making it a useful reference for developers using or maintaining the code.

  • Inheritance and Subclassing

Superclass Initialization: In the context of inheritance, the __init__ method is often used to call the initializer of the superclass using super().__init__(). This ensures that the initialization code of both the superclass and the subclass is executed.

Extending Initialization: Subclasses can extend the behavior of the __init__ method by adding additional attributes or modifying the existing ones, allowing for customization while reusing the initialization logic of the superclass.

Syntax of init in Python

The syntax of the __init__ function is straightforward. It is a method within a class, and it always takes at least one parameter, conventionally named self. This parameter refers to the instance of the class that is being created. Additionally, you can include other parameters in the __init__ method to accept values that will be used to initialize the object's attributes.

class MyClass:
    def __init__(self, parameter1, parameter2):
        # Initialization code here
        self.attribute1 = parameter1
        self.attribute2 = parameter2

The __init__ method can be customized to take any number of parameters based on the specific needs of your class. The self parameter is a reference to the instance of the class and is used to access and modify attributes within the class.

How the __init__ Function is Called Automatically?

The __init__ function is called automatically when an instance of a class is created. When you create an object using the class name followed by parentheses, e.g., my_instance = MyClass(), Python implicitly calls the __init__ method for that instance.

my_instance = MyClass(parameter1_value, parameter2_value)

During this object creation process, any parameters passed within the parentheses are automatically passed to the __init__ method. This allows you to customize the initialization of each instance based on the values provided.

Role of self Parameter

The self parameter in the __init__ method is a convention in Python classes. It represents the instance of the class and is used to access and manipulate the attributes of that instance. When the __init__ method is called during object creation, the self parameter is automatically set to the instance being created.

class MyClass:
    def __init__(self, attribute_value):
        self.attribute = attribute_value
# Creating an instance of MyClass
my_instance = MyClass("some_value")
# Accessing the attribute using the 'self' parameter
print(my_instance.attribute)  # Output: some_value

By convention, the first parameter of every method in a class, including __init__, is self. This convention helps in distinguishing instance variables from local variables and allows for consistent and readable code in the context of object-oriented programming in Python.

Setting Up Instance Variables in __init__ function

Instance variables are variables that belong to an instance of a class. They represent the attributes or properties of an object and are unique to each instance. These variables store data that varies from one object to another, allowing each instance to have its own state.

In Python, instance variables are typically defined within methods, and the __init__ method is a common place for their initialization. Instance variables play a crucial role in encapsulating the state of an object, making it possible to create multiple instances of a class, each with its own set of attributes.

The __init__ function is the ideal place to set up and initialize instance variables for an object. Inside the __init__ method, you define instance variables using the self parameter, and you assign initial values based on the parameters passed during object creation.

class MyClass:
    def __init__(self, attribute1, attribute2):
        # Setting up instance variables
        self.attribute1 = attribute1
        self.attribute2 = attribute2

In this example, attribute1 and attribute2 are instance variables, and their values are assigned to the corresponding attributes of the object (self.attribute1 and self.attribute2). These variables can then be accessed and modified throughout the class methods.


Let's consider a more detailed example:

class Car:
    def __init__(self, make, model, year, color):
        # Initializing instance variables
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        self.mileage = 0  # Default mileage is set to 0 when a new car is created
    def display_info(self):
        print(f"{self.year} {self.make} {self.model} ({self.color})")
# Creating instances of the Car class
car1 = Car("Toyota", "Camry", 2022, "Blue")
car2 = Car("Honda", "Accord", 2021, "Red")
# Accessing instance variables
car1.display_info()  # Output: 2022 Toyota Camry (Blue)
car2.display_info()  # Output: 2021 Honda Accord (Red)

In this example, the Car class has instance variables like make, model, year, color, and mileage. The __init__ method initializes the first four, and a default value for mileage is set. The display_info method then uses these instance variables to print information about each car.

Using Default Parameter Values in __init__

Default parameter values in the __init__ method in Python allow you to provide a default value for a parameter in case it is not explicitly specified during the object creation. This is useful when you want to offer flexibility in creating instances by allowing some parameters to be optional.

class Book:
    def __init__(self, title, author, publication_year=2022):
        # Initializing instance variables
        self.title = title = author
        self.publication_year = publication_year

In this example, publication_year is a parameter with a default value of 2022. If a value for publication_year is not provided during the creation of a Book instance, it will default to 2022.

Using Optional Parameters in __init__

Optional parameters are parameters that are not required during object creation but can be included if needed. You can achieve this by including parameters in the __init__ method without providing default values.

class Person:
    def __init__(self, name, age=None, occupation=None):
        # Initializing instance variables = name
        self.age = age
        self.occupation = occupation

In this example, both age and occupation are optional parameters. If values for these parameters are not provided during the creation of a Person instance, they will default to None.

__init__ with Inheritance

You must have noticed that in a family, a few people have the same texture of hair, such as curly or straight. Some family members look quite identical. This is because genes pass from parents to children through a process known as inheritance

Inheritance is a fundamental cornerstone in object-oriented programming and is often used while writing OOP code. It is the capability of a new class to acquire or inherit the attributes and properties of an existing class. 

The class inheriting the behavior of another class is known as the derived class, and the class whose properties have been acquired is known as the base class. So, the child class inherits methods and attributes of the parent class while adding more unique methods and attributes. 

Inheritance in Python allows a class (subclass/derived class) to inherit attributes and methods from another class (superclass/base class). When using __init__ with inheritance, the super() function is commonly employed to invoke the initializer of the superclass before adding or overriding functionality in the subclass.


Here's an example to illustrate __init__ with inheritance:

class Animal:
    def __init__(self, species):
        self.species = species
    def make_sound(self):
        print("Some generic animal sound")
class Dog(Animal):
    def __init__(self, name, breed):
        # Call the __init__ of the superclass (Animal)
        # Initialize additional attributes specific to Dog = name
        self.breed = breed
    def make_sound(self):
        print("Woof! Woof!")
    def display_info(self):
        print(f"Name: {}, Breed: {self.breed}, Species: {self.species}")
# Creating instances of the Dog class
dog_instance = Dog(name="Buddy", breed="Labrador")
# Accessing methods and attributes

In this example:

  • The Animal class has an __init__ method that initializes the species attribute.

  • The Dog class inherits from Animal using class Dog(Animal):.

  • In the __init__ method of the Dog class, super().__init__(species="Dog") is used to call the initializer of the Animal class. This ensures that the species attribute is set to "Dog."

  • The Dog class introduces additional attributes (name and breed) and overrides the make_sound method.

  • An instance of the Dog class (dog_instance) is created, and its methods are called.

Learn Next:

More Tutorials:

Compilers to Practice Online:

Did you find this article helpful?