How to use the __init__() function in Python
In Python, the __init__() function is a special method used to initialize an instance of a class. When a class instance is created using ClassName(), the __init__() method is automatically called.
The main purpose of the __init__() method is to set the initial attributes of a class. In this method, we can define the class’s attributes and assign initial values to them. This allows for setting the initial values of these attributes directly when creating an instance of the class, without needing to separately assign values to each attribute later on.
Here is a sample code demonstrating the use of the __init__() method:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.name) # 输出:Alice
print(person1.age) # 输出:25
print(person2.name) # 输出:Bob
print(person2.age) # 输出:30
In the code above, the Person class has two attributes, name and age. The __init__() method takes two parameters, name and age, and uses them to initialize the name and age attributes of the instance. By creating an instance of the Person class and passing the appropriate parameters, you can set the initial values of the name and age attributes for each instance.