转载自 http://blog.csdn.net/carolzhang8406/article/details/6856056
1 如果在类中同时定义了__init__和__new__,在创建对象的时候会有优先使用__new__
如
class A(object):
def __init__(self):
print("in init")
def __new__(self):
print("in new")
A()
2new方法会返回所构造的对象,init则不会,在使用new返回对象的时候会隐式调用init函数。new函数必须以cls作为第一个参数,而init则以self作为其第一个参数
实例:
class A(object):
def __new__(cls, *args, **kwds):
print "one"
print "A.__new__", args, kwds
return object.__new__(B, *args, **kwds)
def __init__(cls, *args, **kwds):
print "two"
print "A.__init__", args, kwds
class B(object):
def __new__(cls, *args, **kwds):
print "three"
print cls
print B
print "B.__new__", args, kwds
return object.__new__(cls, *args, **kwds)
def __init__(cls, *args, **kwds):
print "four"
print "B.__init__", args, kwds
class C(object):
def __init__(cls, *args, **kwds):
print "five"
print "C.__init__", args, kwds
print C()
print "====================="
print A()
print "====================="
print B()
利用new创建一个类的对象的最常用的方法为:super(currentclass, cls).__new__(cls[, ...])
如下列
class A(object):
def __new__(cls):
Object = super(A, cls).__new__(cls)
print "in New"
return Object
def __init__(self):
print "in init"
class B(A):
def __init__(self):
print "in B's init"
B()