What is the purpose of a constructor in Python?
a) To define a method that is called automatically when an object is created
b) To destroy an object
c) To initialize class variables
d) To create an abstract method
Answer:
a) To define a method that is called automatically when an object is created
Explanation:
A constructor in Python is a special method called __init__()
that is automatically invoked when an object of a class is created. The constructor is used to initialize the object’s attributes and perform any setup or initialization tasks required for the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an object of Person class
person = Person("Alice", 30)
person.greet() # Output: Hello, my name is Alice and I am 30 years old.
In this example, the __init__()
method initializes the name
and age
attributes of the Person
class when a new object is created. The constructor ensures that the object is in a valid state before it is used.
Constructors are essential for setting up objects with the necessary initial data and ensuring that they are ready for use immediately after creation.