【发布时间】:2011-01-02 08:06:15
【问题描述】:
我认为你可以在一个类中定义“__init__”或“__new__”,但为什么都在 django.utils.datastructures.py 中定义。
我的代码:
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'
数据结构.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)
在什么情况下会调用SortedDict.__init__。
谢谢
【问题讨论】:
-
做阅读文档,它们很详尽!