possible attribute-oriented class
Ken Newton
krnewton at gmail.com
Thu Sep 3 18:46:01 EDT 2009
I have created the following class definition with the idea of making
a clean syntax for non-programmers to created structured data within a
python environment.
I would appreciate comments on this code. First, is something like
this already done? Second, are there reasons for not doing this? If
this seems OK, how could I clean up the string conversion to have
indented format.
The expected use would have all items in the structure be simple
python types or AttrClass types. Code written in python could walk the
structure in a simple way to locate any desired values. Code in a
C/C++ extension should also be able to walk the structure to use any
value in the structure.
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
=========
test() gives the following output:
----
{
second : 2
fifth : 5
fourth : {
aaa : AAA
bbb : BBB}
third : three
first : 1}
AttrClass({'second': 2, 'fifth': 5, 'fourth': AttrClass({'aaa': 'AAA',
'bbb': 'BBB'}), 'third': 'three', 'first': 1})
AAA
----
Ken Newton
More information about the Python-list
mailing list