Published Aug. 3, 2023, 1:31 p.m.
In Python, a constructor is a special method that gets called automatically at the time of object creation. The constructor's name should be __init__(self)
, and its main purpose is to declare and initialize instance variables. If we don't provide a constructor, Python will provide a default constructor.
Let's create a class Car
with a constructor that initializes the make
and model
attributes.
class Car:
def __init__(self, make, model):
# Constructor with `self` and two arguments `make` and `model`
self.make = make
self.model = model
def get_info(self):
# Method to get car information
return f"This car is a {self.make} {self.model}."
Now, let's create an instance of the Car
class and call the get_info()
method.
# Create a car instance using the constructor
car1 = Car("Toyota", "Corolla")
# Call the method to get car information
print(car1.get_info())
This car is a Toyota Corolla.
We define a class Car
with a constructor __init__
, which takes three parameters: self
, make
, and model
. The self
parameter is required in all instance methods to refer to the instance itself.
Inside the constructor, we use the self
variable to initialize the instance variables make
and model
. For example, self.make = make
assigns the value of the make
parameter to the make
attribute of the instance.
We define another method called get_info()
that uses the self
variable to access the instance attributes and returns a formatted string with the car's make and model.
We create an instance of the Car
class called car1
by passing the arguments "Toyota"
and "Corolla"
to the constructor.
We call the get_info()
method on the car1
instance, which returns the formatted car information.
If we don't provide any constructor, Python will provide a default constructor for us.
class Student:
def set_details(self, name, age):
# Method to set student details
self.name = name
self.age = age
def display_details(self):
# Method to display student details
return f"Name: {self.name}, Age: {self.age}"
Now, let's create an instance of the Student
class, set the details using the set_details()
method, and then display the details using the display_details()
method.
# Create a student instance (Python will use the default constructor)
student1 = Student()
# Set the student details using the method
student1.set_details("Alice", 20)
# Display the student details using the method
print(student1.display_details())
Name: Alice, Age: 20
We define a class Student
without providing any constructor. Since we didn't provide a constructor, Python automatically provides a default constructor.
We define two methods: set_details()
and display_details()
. The set_details()
method sets the name
and age
attributes using the self
variable, and the display_details()
method displays the student's name and age.
We create an instance of the Student
class called student1
. Since we didn't provide a constructor, Python uses the default constructor to create the instance.
We call the set_details()
method on the student1
instance to set the student's name and age.
We call the display_details()
method on the student1
instance to display the student's name and age.
In this example, we see that even without explicitly providing a constructor, Python provides a default constructor that allows us to create instances of the class and set attributes dynamically. However, it is recommended to define a constructor explicitly when you need to initialize instance variables during object creation.
class MyClass:
def __init__(self):
print("Constructor is executed.")
self.counter = 0
def increment_counter(self):
self.counter += 1
def get_counter(self):
return self.counter
# Create instances of the class
obj1 = MyClass()
obj2 = MyClass()
# Call methods on each instance
obj1.increment_counter()
obj1.increment_counter()
obj2.increment_counter()
# Display the counter for each instance
print("Counter for obj1:", obj1.get_counter())
print("Counter for obj2:", obj2.get_counter())
Constructor is executed.
Constructor is executed.
Counter for obj1: 2
Counter for obj2: 1
We define a class MyClass
with a constructor __init__
. In the constructor, we print a message "Constructor is executed."
and initialize an instance variable counter
to 0.
We define two methods: increment_counter()
and get_counter()
. The increment_counter()
method increments the counter
attribute, and the get_counter()
method returns the value of the counter
.
We create two instances of the MyClass
class: obj1
and obj2
.
When we create each instance, the constructor __init__
is executed once for each object. In this case, the message "Constructor is executed."
is printed twice, indicating that the constructor is executed once per object.
We call the increment_counter()
method on obj1
twice and on obj2
once.
After calling the methods, we display the values of the counter
attribute for each object using the get_counter()
method. obj1
has a counter value of 2, and obj2
has a counter value of 1, showing that the counter
attribute is separate and maintains its state for each instance.
self
parameter.self
to perform their operations.__init__
, and it is used to initialize the object's attributes (instance variables).None
.Let's consider a real-life example of a Car
class to understand the differences between methods and constructors.
class Car:
def __init__(self, make, model):
# Constructor to initialize make and model attributes
self.make = make
self.model = model
self.speed = 0
def accelerate(self, increment):
# Method to accelerate the car's speed
self.speed += increment
def brake(self, decrement):
# Method to apply the car's brakes
if self.speed >= decrement:
self.speed -= decrement
else:
self.speed = 0
def get_speed(self):
# Method to retrieve the car's current speed
return self.speed
In this example, the Car
class represents a car object with attributes make
, model
, and speed
. The __init__
constructor initializes the make
and model
attributes with the provided values during object creation. The speed
attribute is set to 0 by default.
accelerate(self, increment)
: This method takes an increment
parameter and increases the car's speed by the specified increment.
brake(self, decrement)
: This method takes a decrement
parameter and reduces the car's speed by the specified decrement. If the car's speed becomes negative due to excessive braking, the speed is set to 0.
get_speed(self)
: This method returns the car's current speed.
# Create a car instance and initialize its make and model using the constructor
my_car = Car("Toyota", "Corolla")
# Accelerate the car
my_car.accelerate(30)
# Display the current speed using the method
print("Current speed:", my_car.get_speed()) # Output: Current speed: 30
# Apply the brakes to slow down the car
my_car.brake(10)
# Display the current speed again
print("Current speed:", my_car.get_speed()) # Output: Current speed: 20
In this example, we create a car object using the Car
class and use the accelerate()
and brake()
methods to increase and decrease the car's speed. The constructor (__init__
) is called only once during the object's creation to set the initial values of make
and model
. The methods are called multiple times to perform specific actions on the car object.