标签:
This method is only used for new-style classes (classes inheriting from object).
Called to create a new instance of class cls. new is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of new should be the new object instance (usually an instance of cls).
Typical implementations create a new instance of the class by invoking the superclass’s new method using “super(currentclass, cls).new(cls[, …])” with appropriate arguments and then modifying the newly-created instance as necessary before returning it.
If new returns an instance of cls, then the new instance’s init method will be invoked like “init(self[, …])”, where self is the new instance and the remaining arguments are the same as were passed to new.
If new does not return an instance of cls, then the new instance’s init method will not be invoked.
[new]] is intended mainly to allow subclasses of immutable types (like [int, str, or tuple) to customize instance creation.
class A(object):
a = 1
def __new__(cls, *args, **kwargs):
print ‘+ A new‘
inst = super(A, cls).__new__(cls, *args, **kwargs)
print ‘- A new‘
#return inst
def __init__(self):
print ‘+ A init‘
print ‘- A init‘
a = A()
print type(a)
+ A new
- A new
<type ‘NoneType‘>
class A(object):
a = 1
def __new__(cls, *args, **kwargs):
print ‘+ A new‘
inst = super(A, cls).__new__(cls, *args, **kwargs)
print ‘- A new‘
return inst
def __init__(self):
print ‘+ A init‘
print ‘- A init‘
a = A()
print type(a)
结果
+ A new
- A new
+ A init
- A init
<class ‘__main__.A‘>
class A(object):
_inst = None
def __new__(cls, *args, **kwargs):
print ‘+ A new‘
if not cls._inst:
print ‘do new.‘
cls._inst = super(A, cls).__new__(cls, *args, **kwargs)
cls._inst.inst_count = 0
print ‘- A new‘
return cls._inst
def __init__(self):
print ‘+ A init‘
self.inst_count += 1
print ‘- A init‘
a = A()
print type(a), a.inst_count
aa = A()
print type(aa), aa.inst_count
aaa = A()
print type(aaa), aaa.inst_count
+ A new
do new.
- A new
+ A init
- A init
<class ‘__main__.A‘> 1
+ A new
- A new
+ A init
- A init
<class ‘__main__.A‘> 2
+ A new
- A new
+ A init
- A init
<class ‘__main__.A‘> 3
标签:
原文地址:http://www.cnblogs.com/ordeder/p/5636947.html