new() 方法主要存在于Python2的新式类和Python3中。它是负责创建类实例的静态方法。
当Python实例化一个对象时,首先调用__new__()方法构造一个类的实例,并为其分配对应类型的内存空间,该实例的内存地址就是它的唯一标识符。然后再调用__init__()方法对实例进行初始化,通常是对该实例的属性进行初始化。
以下用几个实例来说明:
实例1:先调用__new__()方法再调用__init__()方法
class Person(object):
def __new__(cls):
print("__new__ called")
return super().__new__(cls)
def __init__(self):
print("__init__ called")
a = Person()
结果:
__new__ called
__init__ called
实例2:new()方法构造一个类实例,并将该实例传递给自身的__init__()方法,即__init__()方法的self
参数。
class Person(object):
def __new__(cls):
print("__new__ called")
instance = super().__new__