Sobes.tech
Junior — Middle

What is the role of the __init__ method in class definition and its objects?

sobes.tech AI

Answer from AI

The init method in Python is the class constructor that is automatically called when a new object is created. It initializes the object's attributes, setting the initial state.

Example:

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

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

Without init, an object would be created without initial values, which makes working with it more difficult.

What is the role of the __init__ method in class… - sobes.tech