Constructor
A special method called when an object is created.
Introduction
In Python, a constructor is a special method that is automatically called when an object of a class is created.
It is defined using the __init__()
method. The constructor initializes the object's attributes and performs any setup
required when the object is created.
class ClassName:
def __init__(self, parameters):
# Initialize attributes here
self.attribute = parameters
Key Points:
- Special Method: The constructor method is always named
__init__
. - First Parameter: The first parameter of
__init__
is alwaysself
, which refers to the instance of the class being created. - Optional Parameters: Constructors can accept additional parameters for initializing specific attributes.
- Automatic Call: The constructor is invoked automatically when an object is instantiated.
Example 1: Basic Constructor
class Person:
def __init__(self, name, age):
self.name = name # Initialize name attribute
self.age = age # Initialize age attribute
# Create an instance of the Person class
person1 = Person("Jasmeet", 30)
print(person1.name) # Output: Jasmeet
print(person1.age) # Output: 30
Example 2: Default Values in Constructor
class Car:
def __init__(self, make, model, year=2020): # Default value for year
self.make = make
self.model = model
self.year = year
car1 = Car("Toyota", "Corolla")
print(car1.year) # Output: 2020
car2 = Car("Tesla", "Model S", 2022)
print(car2.year) # Output: 2022
Example 3: Constructor with No Parameters
class SimpleClass:
def __init__(self):
self.message = "Hello, World!"
obj = SimpleClass()
print(obj.message) # Output: Hello, World!
Advantages of Constructors:
- Encapsulation: Helps initialize the object's attributes at the time of creation.
- Ease of Use: Automatically sets up the object, making it easier to work with classes.
No questions available.