The __init__() method in Python is a special method that runs automatically when an object
of a class is created. It is called the constructor because it is used to initialize (set up) the
object with some values.
Simple Explanation:
When you create an object, Python automatically calls __init__().
It helps to assign values to the object’s attributes at the time of creation.
self is used to refer to the current object.
Example:
class Person:
def __init__(self, name, age):
self.name = name # Assigning value to the 'name' attribute
self.age = age # Assigning value to the 'age' attribute
def show_info(self):
print(f"My name is {self.name} and I am {self.age} years old.")
# Creating an object of the Person class
p1 = Person("Chhavi", 22)
p1.show_info() # Output: My name is Chhavi and I am 22 years old.
Why __init__() is Important:
1. Automatic Initialization:
o It runs automatically when an object is created, saving time and effort.
o Without __init__(), we would have to set values manually after creating an
object.
2. Defines Object Attributes:
o It helps define attributes (variables) specific to each object.
o Example: If you create multiple Person objects, each can have a different
name and age.
3. Improves Code Readability & Organization:
o Makes code cleaner by ensuring every object starts with valid data.
o Avoids writing extra lines of code to set values later.
4. Encapsulation & Object-Oriented Programming (OOP):
o Helps in implementing OOP concepts by binding data (attributes) with
objects.