How is the function __init__ used in Python?

In Python, __init__ is a special method used to initialize an object. This method is automatically called when creating an object and can also be used to pass parameters during object creation.

Here is an example using the __init__ method:

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

person1 = Person("Alice", 25)
print(person1.name)  # 输出:Alice
print(person1.age)  # 输出:25

In the example above, the Person class has an __init__ method which takes two parameters, name and age. When creating the person1 object, the corresponding arguments were passed in, which were used to initialize the object’s name and age attributes.

The self parameter represents the instance itself, it is necessary and used within the method body to access the instance’s attributes and methods.

By using the __init__ method, we can initialize an object during its creation, avoiding the need to manually set attribute values afterwards. This can improve the code’s readability and maintainability.

bannerAds