Python `__new__` 和 `__init__` 的区别

这两个东西看起来很相似, 但有什么区别呢 ?

__init__ 不能返回实例, __new__ 可以


return cls

class Hello(object):
def __init__(self):
print "__init__ invoked."
return self

hello = Hello()

错误结果

__init__ invoked.
Traceback (most recent call last):
File "./class_hello.py", line 12, in <module>
hello = Hello()
TypeError: __init__() should return None, not 'Hello'

__new__ 会先被调用


代码

class Hello(object):
def __new__(cls):
print "__new__ invoked."
return super(Hello, cls).__new__(cls)

def __init__(self):
print "__init__ invoked."

hello = Hello()

结果

python ./class_hello.py
__new__ invoked.
__init__ invoked.

这种结果是因为 __new__ 是控制实例生成的过程, 而 __init__ 是对已经生成的实例进行初始化的过程.
__new__ 方法像是一个类方法,而 __init__ 像是个实例方法.

如果不是返回实例(比如这里返回 cls ), __init__ 不会被调用


class Hello(object):
def __new__(cls):
print "__new__ invoked."
return cls

def __init__(self):
print "__init__ invoked."

hello = Hello()

结果

python ./class_hello.py
__new__ invoked.

参考


http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init