在Python中使用有序字典作为对象字典

发布于 2024-07-11 20:55:01 字数 825 浏览 14 评论 0 原文

我不知道为什么这不起作用:

我正在使用 PEP 372 的 ">odict 类,但我想将其用作 __dict__ 成员,即:

class Bag(object):
    def __init__(self):
        self.__dict__ = odict()

但由于某种原因我得到了奇怪的结果。 这有效:

>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2

但是尝试访问实际的字典不起作用:

>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])

而且变得更奇怪:

>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])

我感觉很愚蠢。 你能帮我吗?

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, i.e.:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

星軌x 2024-07-18 20:55:01

我能找到的最接近您问题的答案是 http ://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html

基本上,如果 __dict__ 不是实际的 dict(),那么它将被忽略,并且属性查找失败。

另一种方法是使用 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)])

The closest answer to your question that I can find is at 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.

The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly.

>>> 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)])
咆哮 2024-07-18 20:55:01

sykora的回答中的一切都是正确的。 这是一个更新的解决方案,具有以下改进:

  1. 即使在访问 a.__dict__ 的特殊情况下也能工作,直接
  2. 支持 copy.copy()
  3. 支持 ==!= 运算符
  4. 使用 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)

Everything in sykora's answer is correct. Here's an updated solution with the following improvements:

  1. works even in the special case of accessing a.__dict__ directly
  2. supports copy.copy()
  3. supports the == and != operators
  4. uses collections.OrderedDict from Python 2.7.

...

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)
人│生佛魔见 2024-07-18 20:55:01

如果您正在寻找具有对 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']

披露:我创作了这个库。 认为这可能对未来的搜索者有所帮助。

If you're looking for a library with attribute access to OrderedDict, the orderedattrdict package provides this.

>>> 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文