Pregunta

No sé por qué esto no funciona:

Estoy usando la clase odict de PEP 372 , pero quiero usarlo como __dict __ miembro, es decir:

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

Pero por alguna razón obtengo resultados extraños. Esto funciona:

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

Pero intentar acceder al diccionario real no funciona:

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

Y se pone más raro:

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

Me siento muy estúpido. ¿Me pueden ayudar?

¿Fue útil?

Solución

La respuesta más cercana a su pregunta que puedo encontrar está en http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html .

Básicamente, si __dict__ no es un dict () real, entonces se ignora y la búsqueda de atributos falla.

La alternativa para esto es usar el odict como miembro y anular los métodos getitem y setitem en consecuencia.

>>> 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)])

Otros consejos

Todo en la respuesta de sykora es correcto. Aquí hay una solución actualizada con las siguientes mejoras:

  1. funciona incluso en el caso especial de acceder a a .__ dict__ directamente
  2. admite copy.copy()
  3. admite los operadores == y ! =
  4. usa collections.OrderedDict de 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)

Si está buscando una biblioteca con acceso de atributo a OrderedDict, el paquete orderedattrdict proporciona esto.

>>> 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']

Divulgación: escribí esta biblioteca. Pensé que podría ayudar a los futuros buscadores.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top