A constructor is a special method in a class that runs automatically when an object is created.
In Python, the constructor method is called __init__().
It is used to:
- Initialize object data
- Assign values to attributes
- Set up the object when it is created
BASIC SYNTAX
class ClassName:
def __init__(self):
# initialization code
SIMPLE EXAMPLE
class Student:
def __init__(self):
print("Constructor is called.")s1 = Student()
When the object s1 is created, the constructor runs automatically.
CONSTRUCTOR WITH PARAMETERS
Most constructors accept parameters to initialize object attributes.
class Student:
def __init__(self, name, age):
self.name = name
self.age = ages1 = Student("Hira", 22)print(s1.name)
print(s1.age)
Explanation:
__init__is the constructorselfrefers to the current objectnameandageare object attributes
DEFAULT CONSTRUCTOR
If you do not define a constructor, Python automatically provides a default constructor that does nothing.
class Car:
passcar1 = Car()
This works even without __init__().
TYPES OF CONSTRUCTORS
1. Default Constructor
No parameters except self.
class Example:
def __init__(self):
print("Default constructor")
2. Parameterized Constructor
Accepts arguments.
class Example:
def __init__(self, value):
self.value = value
MULTIPLE OBJECTS WITH CONSTRUCTOR
class Car:
def __init__(self, brand):
self.brand = brandcar1 = Car("Toyota")
car2 = Car("BMW")print(car1.brand)
print(car2.brand)
Each object has its own data.
IMPORTANT POINTS
• Constructor name must be __init__
• It runs automatically when object is created
• Used to initialize object attributes
• self is required as the first parameter
KEY TAKEAWAY
A constructor initializes the object when it is created.
It helps assign values and prepare the object for use in a clean and structured way.