Python
init method
self keyword
object-oriented programming
Python functions

What do __init__ and self do in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python, understanding the special method __init__ and the keyword self is fundamental to working with classes and objects. These constructs are intrinsic to Python's object-oriented programming paradigm, allowing for organized and modular code. This article delves into the technicalities and applications of __init__ and self with examples and supplementary information.

The Purpose of __init__

Technical Explanation

__init__ is a special method, known as a constructor in object-oriented terms. It's automatically called when a new instance of a class is created. The primary role of __init__ is to initialize the newly created object and to set various instance variables to particular values.

When you define a class in Python and do not provide an __init__ method, Python automatically provides a default one that does nothing. However, in most practical applications, explicitly defining __init__ allows you to pass arguments at the time of object creation and set up the object in a specific way.

Syntax and Example

Here's the basic syntax and a simple example:

python
1class Car:
2    def __init__(self, make, model, year):
3        self.make = make
4        self.model = model
5        self.year = year
6
7my_car = Car("Toyota", "Corolla", 2021)

In this example:

  • __init__ takes make, model, and year as arguments.
  • The method assigns these values to self.make, self.model, and self.year.
  • Upon creating my_car, __init__ is called, initializing the object's attributes with specified values.

Understanding self

Functionality of self

self in Python is akin to this in languages like Java and C++. It represents the instance of the class and is used to access variables that belong to the class. Whenever a class method is called on an object, self is the first parameter that automatically receives the object itself.

Importance of self

  • Differentiating Objects: Each object in Python may have different values for its attributes, and self helps keep these values distinguished between various instances.
  • Access to Attributes and Methods: self is used to access attributes and methods of the class within class methods.

Example and Illustration

Building on the previous Car class example:

python
1def display_info(self):
2    print(f"Car: {self.year} {self.make} {self.model}")
3
4car1 = Car("Honda", "Civic", 2020)
5car2 = Car("Ford", "Mustang", 2022)
6
7car1.display_info()  # Output: Car: 2020 Honda Civic
8car2.display_info()  # Output: Car: 2022 Ford Mustang
  • Here, display_info is a method that uses self to access instance attributes.
  • When display_info is called, self ensures it works with the right instance (car1 or car2).

Common Misconceptions

self as a Keyword

It's a convention, not a keyword. While self is usually the first parameter of any method in a class, you could name it differently. However, using the name self is strongly encouraged for readability and consistency across Python codebases.

__init__ vs Other Methods

Some might think __init__ is the only method that starts and ends with double underscores (__), while it's not. Python has several special methods (also called "dunder" methods) like __str__, __repr__, and __eq__ for providing specific functionalities to the objects of the class.

Summary Table

Below is a summary table highlighting key points about __init__ and self:

FeatureDescription
__init__Special method called automatically when an object is instantiated
PurposeInitializes attributes of the class
Syntaxdef __init__(self, args):
selfRepresents the instance of the class and is the first parameter of any method
FunctionalityAllows access to instance variables and methods
ImportanceDifferentiates between different instances and allows easy method binding
NamingConvention rather than a keyword

Additional Details

Alternate Use Cases

  1. Default Values: Providing default values in __init__ for optional parameters:
python
1   class Book:
2       def __init__(self, title, author="Unknown"):
3           self.title = title
4           self.author = author
  1. Initial Computation: Performing calculations or setting up resources upon object creation.
python
1   class Circle:
2       def __init__(self, radius):
3           self.radius = radius
4           self.area = 3.14 * (radius ** 2)

By understanding __init__ and self, you gain valuable insight into class behavior and can construct object-oriented programs more effectively.


Course illustration
Course illustration

All Rights Reserved.