A Constructor is a special method that is automatically called when an object is created. In Python, the constructor is defined using the __init__() method.
Constructors are mainly used to initialize object attributes.
Default Constructor
A constructor that does not accept any additional parameters is called a default constructor.
Example
class Student:
def __init__(self):
print("Constructor Called")
student = Student()
Output:
Constructor Called
Parameterized Constructor
A constructor that accepts parameters is called a parameterized constructor.
Example
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("John", 20)
print(student.name)
print(student.age)
Output:
John
20
Constructor with Default Values
Example
class Student:
def __init__(self, name="Guest"):
self.name = name
student1 = Student()
student2 = Student("Alice")
print(student1.name)
print(student2.name)
Output:
Guest
Alice
Using Constructor with Methods
Example
class Student:
def __init__(self, name):
self.name = name
def show(self):
print("Student Name:", self.name)
student = Student("John")
student.show()
Output:
Student Name: John
Multiple Object Creation
Example
class Student:
def __init__(self, name):
self.name = name
student1 = Student("John")
student2 = Student("Alice")
print(student1.name)
print(student2.name)
Output:
John
Alice
Constructor with Calculations
Example
class Rectangle:
def __init__(self, length, width):
self.area = length * width
rectangle = Rectangle(10, 5)
print(rectangle.area)
Output:
50
Constructor Inheritance Example
Example
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
pass
student = Student("John")
print(student.name)
Output:
John
Summary
- Constructors are special methods used to initialize objects.
- Python uses the
__init__()method as a constructor. - Constructors are called automatically when an object is created.
- Constructors can accept parameters.
- Default values can be provided in constructors.
- Constructors help initialize object attributes.
- Every object gets its own set of initialized values.