Sobes.tech
Junior — Middle

Can you explain the purpose of the __init__ function in Python and how it is used when creating objects?

sobes.tech AI

Answer from AI

The __init__ function in Python is a class constructor that is automatically called when a new object is created. It is used to initialize the object's attributes.

Example of usage:

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

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

Here, __init__ takes parameters name and age and assigns them to the object's attributes self. This allows setting the initial state of the object immediately upon creation.

Can you explain the purpose of the __init__ function… - sobes.tech