Junior — Middle
Can you explain what a constructor is in the context of object-oriented programming?
sobes.tech AI
Answer from AI
A constructor is a special method of a class in object-oriented programming that is called when a new object of that class is created. Its main task is to initialize the object, that is, to set the initial values of its properties and perform necessary configurations.
For example, in Python, the constructor is called __init__:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Ivan", 30)
Here, when the object p is created, the constructor is automatically called, which sets the name and age.