__new__ 用于新建对象, __init__ 用于初始化对象。我们在定义 __init__ 的时候会传入一个 self 参数表示对象本身,而 __new__ 就是在 __init__ 调用之前把这个对象 (self) 制造出来。
class A():
def __new__(cls):
print("A.__new__ called")
return super(A, cls).__new__(cls)
def __init__(self):
print("A.__init__ called")
A()
# 输出
A.__new__ called
A.__init__ called
可以看到 __new__ 会返回值,而 __init__ 不返回值。可以这样理解,__new__ 创建了一只没毛的鸟(调用时创建一个“空”的对象,各项属性为空),然后 __init__ 负责添加毛(调用时会给这个新对象的各个属性赋值)。
来自 stackoverflow 的解释
__new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.
网友评论