Junior — Middle
Explain the purpose and function of a constructor in object-oriented programming.
sobes.tech AI
Answer from AI
In object-oriented programming, a constructor is a special class method that is automatically called when a new object of that class is created. Its main purpose is to initialize the object, that is, to set initial attribute values and perform necessary preparatory actions.
In Python, the constructor is implemented using the __init__ method. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Ivan", 30)
print(p.name) # Ivan
Here, when creating a Person object, __init__ is automatically called, which sets the name and age.