__new__方法实际上在__init__方法之前执行, 用于创建类的实例; __init__方法负责在实例创建后对其进行自定义.
__new__方法会返回一个创建的实例,而init什么都不返回.
参数在调用类构造函数时首先被传递给new方法, 然后再传递给init方法.
class Person(object):
def __init__(self, name):
print "__init__ called"
self.name = name
person = Person("mike")
输出为:
__init__ called
上述过程实际执行的顺序如下:
class Person(object):
def __new__(cls, name):
print "__new__ called first"
return super(Person, cls).__new__(cls, name)
def __init__(self, name):
print "__init__ called"
self.name = name
person = Person('mike')
输出为:
__new__ called first
__init__ called