通常我们把 __init__ 称为构造方法,这是从其他语言借鉴过来的术语。
用于构建实例的是特殊方法 __new__:这是个类方法,必须返回一个实例,返回的实例会作为第一个参数(即self)传给 __init__ 方法。
调用 __init__ 方法时要传入实例,且禁止返回所以 __init__ 方法其实是初始化方法。
真正的构造方法是 __new__,不需要自己编写 __new__ 方法,从 object 类继承的实现已经足够了。
__new__ 是类方法,第一个参数是类本身,余下的参数与 __init__ 方法一样,只不过没有self。
class A:
def __new__(cls, arg):
print(arg)
print(cls)
return super().__new__(cls)
def __init__(self, num):
print("__init__ : {}".format(num))
>>> a = A(1)
1
<class '__main__.A'>
__init__ : 1
从 __new__ 方法到 __init__ 方法,是最常见的,但不是唯一的。 __new__ 方法也可以返回其他类的实例,此时,解释器不会调用 __init__ 方法。
class A: pass
class B:
def __new__(cls, arg):
print(arg)
print(cls)
return A()
def __init__(self, num):
print("__init__ : {}".format(num))
>>> b=B(1)
1
<class '__main__.B'>