Sobes.tech
Junior — Middle

Kas saaksite selgitada __init__ funktsiooni Pythonis ja kuidas seda kasutatakse objektide loomisel?

sobes.tech AI

Vastus AI-lt

The __init__ function in Python is the class constructor, which is called automatically when a new object is created. It is used to initialize the attributes of the object.

Example:

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 the parameters name and age and assigns them to the object's self attributes. This allows setting the initial state of the object at the moment of its creation.