A constructor is a special method that is commonly used to initialize an object when it is created. In Python, the __init__() method is normally used for this purpose.
A constructor is a method used to initialize the attributes of an object. It allows us to provide initial values when creating an object.
class Student:
def __init__(self):
print("Constructor called")
student = Student()
Output:
Constructor called
The __init__() method is a special instance method commonly used to initialize object attributes.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("Rahul", 20)
print(student.name)
print(student.age)
Output:
Rahul 20
When an object is created, Python automatically calls the __init__() method after the new instance has been created.
class Student:
def __init__(self):
print("Student object initialized")
student = Student()
Output:
Student object initialized
The first parameter of an instance method is conventionally named self. It refers to the current object.
class Student:
def __init__(self, name):
self.name = name
student = Student("Rahul")
print(student.name)
Here, self.name stores the name inside the object.
A constructor can accept parameters so that each object can be initialized with different values.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employee = Employee("Rahul", 30000)
print(employee.name)
print(employee.salary)
Output:
Rahul 30000
The same constructor can initialize different objects with different values.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Rahul", 20)
student2 = Student("Amit", 22)
student3 = Student("Priya", 21)
print(student1.name)
print(student2.name)
print(student3.name)
Output:
Rahul Amit Priya
Constructor parameters can have default values. This allows an object to be created without providing every argument.
class Student:
def __init__(self, name, course="Python"):
self.name = name
self.course = course
student1 = Student("Rahul")
student2 = Student("Amit", "Java")
print(student1.name, student1.course)
print(student2.name, student2.course)
Output:
Rahul Python Amit Java
A constructor can validate data before storing it in an object.
class Student:
def __init__(self, name, age):
if age >= 18:
self.name = name
self.age = age
else:
raise ValueError(
"Age must be 18 or above"
)
student = Student("Rahul", 20)
print(student.name)
Output:
Rahul
A class can contain a constructor as well as other methods.
class Student:
def __init__(self, name, course):
self.name = name
self.course = course
def display(self):
print("Name:", self.name)
print("Course:", self.course)
student = Student(
"Rahul",
"Python"
)
student.display()
Output:
Name: Rahul Course: Python
A constructor can initialize instance variables while the class can also contain class variables shared by instances.
class Student:
school = "Soopro Pathshala"
def __init__(self, name):
self.name = name
student = Student("Rahul")
print(student.name)
print(student.school)
Output:
Rahul Soopro Pathshala
When a child class defines its own __init__(), the parent's initializer is not automatically called. The child can explicitly call the parent initializer using super().
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, course):
super().__init__(name)
self.course = course
student = Student("Rahul", "Python")
print(student.name)
print(student.course)
Output:
Rahul Python
The super() function is useful when a child class needs to reuse initialization logic from its parent class.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Tommy", "Labrador")
print(dog.name)
print(dog.breed)
Output:
Tommy Labrador
A class does not have to define its own __init__() method. Python can still create instances of the class.
class Student:
def display(self):
print("Student")
student = Student()
student.display()
Output:
Student
An initializer can contain only pass if there is currently no initialization logic to perform.
class Student:
def __init__(self):
pass
student = Student()
print("Object created")
Output:
Object created
A constructor can accept many parameters to initialize a complete object.
class Employee:
def __init__(
self,
name,
age,
department,
salary
):
self.name = name
self.age = age
self.department = department
self.salary = salary
employee = Employee(
"Rahul",
25,
"IT",
40000
)
print(employee.name)
print(employee.department)
print(employee.salary)
Output:
Rahul IT 40000
Constructor arguments can be passed using parameter names.
class Student:
def __init__(self, name, age, course):
self.name = name
self.age = age
self.course = course
student = Student(
name="Rahul",
age=20,
course="Python"
)
print(student.name)
print(student.course)
Output:
Rahul Python
Using a mutable object such as a list as a default constructor argument can cause unexpected sharing between instances. A safer approach is to use None and create a new list inside the constructor.
class Student:
def __init__(self, name, subjects=None):
self.name = name
if subjects is None:
subjects = []
self.subjects = subjects
For classes that mainly store data, Python's dataclasses module can automatically generate an initializer and other useful methods.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
student = Student("Rahul", 20)
print(student)
Output:
Student(name='Rahul', age=20)
| Constructor | Normal Method |
|---|---|
| Commonly written as __init__() | Can have any valid method name |
| Used to initialize an object | Used to perform a specific operation |
| Called automatically during initialization | Usually called explicitly |
| Runs as part of object creation | Runs when the method is invoked |
A constructor can initialize a bank account with an account holder and an opening balance.
class BankAccount:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def show_balance(self):
print("Account Holder:", self.name)
print("Balance:", self.balance)
account = BankAccount(
"Rahul",
5000
)
account.show_balance()
Output:
Account Holder: Rahul Balance: 5000
class Student:
school = "Soopro Pathshala"
def __init__(
self,
name,
age,
course
):
self.name = name
self.age = age
self.course = course
def display(self):
print("Name:", self.name)
print("Age:", self.age)
print("Course:", self.course)
print("School:", self.school)
student1 = Student(
"Rahul",
20,
"Python"
)
student2 = Student(
"Amit",
22,
"Java"
)
student1.display()
print()
student2.display()
Output:
Name: Rahul Age: 20 Course: Python School: Soopro Pathshala Name: Amit Age: 22 Course: Java School: Soopro Pathshala
Question: Which special method is commonly used as a constructor in Python?