possible attribute-oriented class
Peter Otten
__peter__ at web.de
Fri Sep 4 03:32:51 EDT 2009
Ken Newton wrote:
> class AttrClass(object):
> """AttrClass lets you freely add attributes in nested manner"""
>
> def __init__(self):
> pass
> def __setitem__(self, key, value):
> return self.__dict__.__setitem__(key, value)
> def __repr__(self):
> return "%s(%s)" % (self.__class__.__name__,
> self.__dict__.__repr__())
> def __str__(self):
> ll = ['{']
> for k,v in self.__dict__.iteritems():
> ll.append("%s : %s" % (k, str(v)))
> return '\n'.join(ll) + '}'
>
> def test():
> atr = AttrClass()
> atr.first = 1
> atr.second = 2
> atr.third = 'three'
>
> atrsub = AttrClass()
> atrsub.aaa = 'AAA'
> atrsub.bbb = 'BBB'
>
> atr.fourth = atrsub
> atr.fifth = 5
>
> print atr
> print
> print repr(atr)
> print
> print atr.fourth.aaa
Just in case you didn't note: your test() function will run successfully
even if you remove the __setitem__() method. Allowing
atr["x"] = 42
but not
print attr["x"]
may puzzle your intended audience.
More information about the Python-list
mailing list