Junior — Middle
What is the role of the __init__ method in a Python class and what does it usually implement?
sobes.tech AI
Answer from AI
The __init__ method in a Python class is a constructor that is automatically called when a new instance of the class is created. Its main role is to initialize the object's attributes, that is, to set the initial state.
Typically, parameters necessary for configuring the object are passed to __init__, and within the method, these parameters are assigned to the instance's attributes.
Example:
class Person:
def __init__(self, name, age):
self.name = name # initialize the name attribute
self.age = age # initialize the age attribute
p = Person('Ivan', 30)
print(p.name) # Ivan
print(p.age) # 30
Thus, __init__ allows setting the necessary data for the object immediately upon creation.