[英]Using an ordered dict as object dictionary in python
I don't know why this doesn't work: 我不知道为什么这不起作用:
I'm using the odict class from PEP 372 , but I want to use it as a __dict__
member, ie: 我正在使用PEP 372中的odict类,但我想将它用作
__dict__
成员,即:
class Bag(object):
def __init__(self):
self.__dict__ = odict()
But for some reason I'm getting weird results. 但由于某种原因,我得到了奇怪的结果。 This works:
这有效:
>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
But trying to access the actual dictionary doesn't work: 但是尝试访问实际的字典不起作用:
>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
And it gets weirder: 它变得更奇怪了:
>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
I'm feeling very stupid. 我感觉非常愚蠢。 Can you help me out?
你能帮我吗?
The closest answer to your question that I can find is at http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html . 我能找到的最接近你问题的答案是http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html 。
Basically, if __dict__
is not an actual dict()
, then it is ignored, and attribute lookup fails. 基本上,如果
__dict__
不是实际的dict()
,则忽略它,并且属性查找失败。
The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly. 另一种方法是使用odict作为成员,并相应地覆盖getitem和setitem方法。
>>> class A(object) :
... def __init__(self) :
... self.__dict__['_odict'] = odict()
... def __getattr__(self, value) :
... return self.__dict__['_odict'][value]
... def __setattr__(self, key, value) :
... self.__dict__['_odict'][key] = value
...
>>> a = A()
>>> a
<__main__.A object at 0xb7bce34c>
>>> a.x = 1
>>> a.x
1
>>> a.y = 2
>>> a.y
2
>>> a.odict
odict.odict([('x', 1), ('y', 2)])
Everything in sykora's answer is correct. sykora答案中的所有内容都是正确的。 Here's an updated solution with the following improvements:
这是一个更新的解决方案,具有以下改进:
a.__dict__
directly a.__dict__
的特殊情况下也能正常工作 copy.copy()
copy.copy()
==
and !=
operators ==
和!=
运算符 collections.OrderedDict
from Python 2.7. collections.OrderedDict
。 ... ...
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)
If you're looking for a library with attribute access to OrderedDict, the orderedattrdict package provides this. 如果您正在寻找具有OrderedDict属性访问权限的库,那么orderedattrdict包就可以提供。
>>> from orderedattrdict import AttrDict
>>> conf = AttrDict()
>>> conf['z'] = 1
>>> assert conf.z == 1
>>> conf.y = 2
>>> assert conf['y'] == 2
>>> conf.x = 3
>>> assert conf.keys() == ['z', 'y', 'x']
Disclosure: I authored this library. 披露:我撰写了这个图书馆。 Thought it might help future searchers.
认为它可能有助于未来的搜索者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.