__init__
是 Python 中的方法或构造函数。当创建类的新对象/实例时,会自动调用此方法来分配内存。 所有类都有 __init__
方法。
例子:
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E_1 = Employee("Yiibai", 20, 25000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E_1.name)
print(E_1.age)
print(E_1.salary)
运行结果如下:
Yiibai
20
25000