用于构建实例的方法是__new__, 必须返回一个实例,返回的实例会作为__init__的第一个参数(self)
__init__方法其实是初始化方法,真正的构造方法是__new__
从__new__方法到__init__是最常见的方法,但是__new__方法也可以返回其他类的实例,此时,解释器不会调用__init__方法
# 构建对象的伪代码 def object_maker(the_class, some_arg): new_object = the_class.__new__(some_arg) if isinstance(new_object, the_class): the_class.__init__(new_object, some_arg) return new_object
# 下述两个语句的作用基本等效 x = Foo('bar') x = object_maker(Foo, 'bar')
当使用type定义一个类时
type(classname, superclasses, attributedict)
当我们调用type, type的__call__方法被调用,__call__方法会调用__new__和__init__
type.__new__(typeclass, classname, superclasses, attributedict) type.__init__(cls, classname, superclasses, attributedict)