Advertisements
Advertisements
Question
Explain Constructor with an example.
Explain
Advertisements
Solution
A constructor is a specialised method within a class that is automatically called the moment an object is created. Its main job is to "set up" the object by assigning initial values to its data members.
Example:
class Car:
# This is the constructor
def __init__(self, brand, year):
self.brand = brand # Initializing the brand attribute
self.year = year # Initializing the year attribute
# Creating an object triggers the constructor automatically
my_car = Car("Toyota", 2022)
print(my_car.brand) # Output: Toyotashaalaa.com
Is there an error in this question or solution?
2023-2024 (July) Official Board Paper
