What do __init__ and self do in Python?
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
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:
In this example:
__init__takesmake,model, andyearas arguments.- The method assigns these values to
self.make,self.model, andself.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
selfhelps keep these values distinguished between various instances. - Access to Attributes and Methods:
selfis used to access attributes and methods of the class within class methods.
Example and Illustration
Building on the previous Car class example:
- Here,
display_infois a method that usesselfto access instance attributes. - When
display_infois called,selfensures it works with the right instance (car1orcar2).
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:
| Feature | Description |
__init__ | Special method called automatically when an object is instantiated |
| Purpose | Initializes attributes of the class |
| Syntax | def __init__(self, args): |
self | Represents the instance of the class and is the first parameter of any method |
| Functionality | Allows access to instance variables and methods |
| Importance | Differentiates between different instances and allows easy method binding |
| Naming | Convention rather than a keyword |
Additional Details
Alternate Use Cases
- Default Values: Providing default values in
__init__for optional parameters:
- Initial Computation: Performing calculations or setting up resources upon object creation.
By understanding __init__ and self, you gain valuable insight into class behavior and can construct object-oriented programs more effectively.
Related reading
- What do and mean in Python?
- What do args and kwargs mean?
- What do double star/asterisk and star/asterisk mean in a function call?
- What do I use for a max-heap implementation in Python?
- What do lambda function closures capture?
- What do square brackets mean in pip install?
- What do the python file extensions, .pyc .pyd .pyo stand for?
- What does -1 in numpy reshape mean?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.