Sobes.tech
Junior — Middle

Explain the purpose and function of a constructor in Python.

sobes.tech AI

Answer from AI

In Python, a constructor is a special class method named __init__. Its main purpose is to initialize a new object after its creation. When an instance of a class is created, __init__ is automatically called, and parameters can be passed to configure the object.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Ivan", 30)
print(p.name)  # Ivan
print(p.age)   # 30

Thus, the constructor allows setting the initial state of the object, assigning values to its attributes, and performing necessary setup.