class attrdict
Hallvard B Furuseth
h.b.furuseth at usit.uio.no
Fri Mar 2 06:04:33 EST 2007
Does this class need anything more?
Is there any risk of a lookup loop?
Seems to work...
class attrdict(dict):
"""Dict where d['foo'] also can be accessed as d.foo"""
def __init__(self, *args, **kwargs):
self.__dict__ = self
dict.__init__(self, *args, **kwargs)
def __repr__(self):
return dict.__repr__(self).join(("attrdict(", ")"))
>>> a = attrdict([(1,2)], a=3, b=4)
>>> a
attrdict({'a': 3, 1: 2, 'b': 4})
>>> a = attrdict([(1,2)], b=3, c=4)
>>> a
attrdict({1: 2, 'c': 4, 'b': 3})
>>> a.b
3
>>> a.d = 5
>>> a['d']
5
>>> a.e
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'attrdict' object has no attribute 'e'
>>> a.__getattr__ = 'xyzzy'
>>> a.__getattribute__ = 'xyzzy'
>>> a.__setattr__ = 'xyzzy'
>>> a.__delattr__ = 'xyzzy'
>>> a.c
4
>>> a[1]
2
>>> del a.c
>>>
--
Hallvard
More information about the Python-list
mailing list