i think you can defined either ‘__init__‘ or ‘__new__‘ in a class,but why all defined in django.utils.datastructures.py.
my code:
class a(object):
def __init__(self):
print 'aaa'
def __new__(self):
print 'sss'
a()#print 'sss'
class b:
def __init__(self):
print 'aaa'
def __new__(self):
print 'sss'
b()#print 'aaa'
datastructures.py:
class SortedDict(dict):
"""
A dictionary that keeps its keys in the order in which they're inserted.
"""
def __new__(cls, *args, **kwargs):
instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrder = []
return instance
def __init__(self, data=None):
if data is None:
data = {}
super(SortedDict, self).__init__(data)
if isinstance(data, dict):
self.keyOrder = data.keys()
else:
self.keyOrder = []
for key, value in data:
if key not in self.keyOrder:
self.keyOrder.append(key)
and what circumstances the SortedDict.__init__ will be call.
thanks
You can define either or both of
__new__and__init__.__new__must return an object — which can be a new one (typically that task is delegated totype.__new__), an existing one (to implement singletons, “recycle” instances from a pool, and so on), or even one that’s not an instance of the class. If__new__returns an instance of the class (new or existing),__init__then gets called on it; if__new__returns an object that’s not an instance of the class, then__init__is not called.__init__is passed a class instance as its first item (in the same state__new__returned it, i.e., typically “empty”) and must alter it as needed to make it ready for use (most often by adding attributes).In general it’s best to use
__init__for all it can do — and__new__, if something is left that__init__can’t do, for that “extra something”.So you’ll typically define both if there’s something useful you can do in
__init__, but not everything you want to happen when the class gets instantiated.For example, consider a class that subclasses
intbut also has afooslot — and you want it to be instantiated with an initializer for theintand one for the.foo. Asintis immutable, that part has to happen in__new__, so pedantically one could code:In practice, for a case this simple, nobody would mind if you lost the
__init__and just moved theself.foo = footo__new__. But if initialization is rich and complex enough to be best placed in__init__, this idea is worth keeping in mind.