new
用于创建对象,是一个静态方法,第一个参数是cls,该方法必须返回一个对象实例,可以return父类__new__()出来的实例,也可以直接将object的__new__()出来的实例返回
class Foo(object):
def __new__(cls, *args, **kwargs):
print '__new__ method called'
return object.__new__(cls, *args, **kwargs) # 必须返回对象实例,否则调用__init__方法
obj = Foo() # 输出 __new__ method called
init
用于对象的初始化,每次调用__init__ 之前,都会先调用__new__
class Foo(object):
def __new__(cls, *args, **kwargs):
print '__new__ method called'
return object.__new__(cls, *args, **kwargs) #A 必须返回对象实例,否则调用__init__方法
def __init__(self, *args, **kwargs):
print '__init__ method called'
obj = Foo() # 先输出:__new__ method called ,再输出: __init__ method called# 注意:如果把 A 行注释,则不会输出 __init__ method called, 因为没有对象实例返回,所以不会调用__init__方法
call
对象可call,是对象,而不是类
class Foo(object):
def __new__(cls, *args, **kwargs):
print '__new__ method called'
return object.__new__(cls, *args, **kwargs) #A 必须返回对象实例,否则调用__init__方法
def __init__(self, *args, **kwargs):
print '__init__ method called'
def __call__(self, *args, **kwargs):
print '__call__ method called'obj = Foo() # 先输出:__new__ method called ,再输出: __init__ method called
obj() # 输出: __call__ method called
取自:http://www.tang-lei.com/2018/08/30/python-详解-new-init-call-方法/