__init__()
What is __init__() ?
__init__() is a constructor method in Python.
It is automatically called when you create an object of a class.
Its main job is:
Initialize (set up) object data (attributes)
Basic Syntax
class ClassName:
def __init__(self, parameters):
# initialization code
• self → refers to the current object
• Runs immediately after object creation
Example 1: Simple Initialization
class Student:
def __init__(self, name):
[Link] = name
s1 = Student("Vijay")
print([Link])
Output:
Vijay
Explanation:
• Student("Vijay") → creates object
• __init__() is called automatically
• [Link] = name → stores "Vijay" inside object
Example 2: Multiple Attributes
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
s1 = Student("Vijay", 22)
print([Link])
print([Link])
Output:
Vijay
22
Think of it like:
__init__() = filling a form when object is created
Example 3: Default Values
class Car:
def __init__(self, brand="Unknown"):
[Link] = brand
c1 = Car()
c2 = Car("Tesla")
print([Link])
print([Link])
Output:
Unknown
Tesla
Important Points
✔ __init__() is not responsible for creating object
• Object is created by __new__()
✔ It only initializes data
✔ It does not return anything
def __init__(self):
return None # implicit
Common Mistake
class Test:
def __init__(self):
return 10 # ERROR
__init__() must return None, otherwise error
Final Summary
__init__() is:
• Automatically called
• Used to initialize object data
• Runs after object creation
• Does not return anything