Sobes.tech
Junior — Middle

What is the role of an initializer in object-oriented programming?

sobes.tech AI

Answer from AI

An initializer in object-oriented programming is a special method that is called when a new object of a class is created to set it up initially.

In Python, this method is __init__, which allows setting initial values for the object's attributes.

Example:

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

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

Thus, the initializer ensures the correct creation of an object with the necessary parameters.