Python
Programming
Object-Oriented Programming
__init__ method
self keyword

What do __init__ and self do in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Python, __init__ and self are fundamental concepts tied to the language's approach to object-oriented programming (OOP). Understanding both is crucial for effectively using Python's classes and objects.

Understanding __init__

The __init__ method in Python is what is known as a constructor in other object-oriented programming languages. It is the first method that’s called when an object is created from a class. The primary purpose of this method is to initialize the attributes of the object.

Example:

python
1class Car:
2    def __init__(self, make, model):
3        self.make = make
4        self.model = model

In this example, the Car class has an __init__ method with parameters make and model. When a Car object is created, these parameters are used to set the make and model attributes of the object.

Understanding self

self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in within its methods. It binds the attributes with the given arguments.

Example:

python
1class Car:
2    def __init__(self, make, model):
3        self.make = make
4        self.model = model
5
6    def display_info(self):
7        return f"Car: {self.make} {self.model}"
8
9# Creating an object of Car
10my_car = Car("Toyota", "Corolla")
11print(my_car.display_info())

In this example, self.make and self.model are used to refer to the attributes set by the __init__ method. The method display_info uses these attributes to return information about the car.

Why self?

In Python, self is explicitly used in method definitions and calls to differentiate between method calls of objects. Unlike languages like Java, where it is optional and implicit, Python requires that it be explicitly stated in both the method parameter and when calling an attribute/method through it.

Table: Summary of __init__ and self

TermDescriptionUsage
__init__Special method used to initialize newly created objects from a class.def __init__(self, <args>):
selfRepresents the instance of the class, allowing access to the class attributes and methods.Used as the first parameter in class methods and to access properties/methods.

Key Considerations

  • __init__ can take any number of parameters and is typically used to initialize attributes of a new object.
  • Although self is a convention, and not a Python keyword, it is universally followed, and it’s recommended to adhere to it for consistency.
  • Python does not support method overloading, including for the __init__ method. However, you can achieve similar functionality by setting default parameter values or by using variable-length argument lists.
  • Always make sure __init__ either explicitly returns None or has no return statement. Any other return value will lead to a TypeError.

Additional Subtopics

  • Dynamic Attributes: Python allows for dynamic attribute creation, meaning attributes can be added to an object on the fly, which is not directly tied to class definitions.
  • Private and Protected Members: Using _ and __ prefixes, Python supports a form of encapsulation by convention (single underscore) and name mangling (double underscores).
  • Destructors: Python uses __del__ method which, unlike __init__, is called when an object is being destroyed. Understanding its usage with respect to __init__ can be crucial for managing resources.

By understanding __init__ and self, programmers can leverage Python’s object-oriented capabilities effectively, making code more modular, reusable, and organized.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.