<p>西科拉的答案都是正确的。下面是一个更新的解决方案,有以下改进:</p>
<ol>
<li>即使在直接访问<code>a.__dict__</code>的特殊情况下也可以工作</li>
<li>支持<code>copy.copy()</code></li>
<li>支持<code>==</code>和<code>!=</code>运算符</li>
<li>使用Python 2.7中的<a href="http://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer">^{<cd5>}</a>。</li>
</ol>
<p>。。。</p>
<pre><code>from collections import OrderedDict
class OrderedNamespace(object):
def __init__(self):
super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )
def __getattr__(self, key):
odict = super(OrderedNamespace, self).__getattribute__('_odict')
if key in odict:
return odict[key]
return super(OrderedNamespace, self).__getattribute__(key)
def __setattr__(self, key, val):
self._odict[key] = val
@property
def __dict__(self):
return self._odict
def __setstate__(self, state): # Support copy.copy
super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )
self._odict.update( state )
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
</code></pre>