The __init__() Method in Python
In Python, every class can have a special method named
__init__().
This method is automatically executed whenever a new object is created from a class.
The main purpose of __init__() is to:
- Initialize object data
- Assign values to object attributes
- Perform setup tasks during object creation
How __init__() Works
When you create an object, Python immediately calls the
__init__() method and passes the provided arguments to it.
Example: Initialize Object Attributes
Here:
-
__init__()assigns initial values to the object - Attributes are created at the time of object construction
Automatic Execution of __init__()
You do not need to call __init__() explicitly.
Python runs it every time a new instance of the class is created.
Creating Objects Without __init__()
If a class does not define an __init__() method, attributes
must be assigned manually.
Example: Manual Attribute Assignment
This approach works but is error-prone and harder to manage, especially in large programs.
Why __init__() Is Important
Using __init__():
- Ensures objects are created in a valid state
- Reduces repetitive code
- Improves readability and reliability
Using Default Values in __init__()
You can provide default values for parameters, making them optional during object creation.
Example: Default Parameter Value
Multiple Parameters in __init__()
The __init__() method can accept any number of parameters,
depending on your class design.
