Junior — Middle
Can you explain the purpose of the __init__ method in a class?
sobes.tech AI
Answer from AI
The __init__ method in Python is a class constructor that is automatically called when a new object of this class is created. Its main task is to initialize the object's attributes by setting initial values.
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
Here, __init__ takes parameters name and age and stores them in the object's attributes self.