Using Python, I'm trying to write object that it's access would be like this:
page[2].records[7].color = "ffff"
(the 'record' has some fields).
the object should be exported to json string and of course import from json (currently unwrittten), so I've added the toString() method.
The point is the code is very "clumsy". Is there way (using python) to make more "comely" code?
my code:
class Record ():
'''
'''
def __init__(self, title, color, action, data) :
self.title = title
self.color = color
self.action = action
self.data = data
def toDict(self) :
ans = {'title':self.title, 'color':self.color, 'action':self.action, 'data':self.data}
return ans
def toString(self):
return '%s' % self.toDict()
#-----------------------------------------------------------------------
class Records():
'''
'''
def __init__(self):
self.f_record = {}
def __getitem__(self, key):
if not(self.f_record.get(key,None)):
self.f_record[key] = Record(None,None,None,None)
return self.f_record[key]
def __setitem__(self, key, value):
self.f_record[key] = value
def toDict(self):
ans = {}
for i in self.f_record:
ans[i] = self.f_record[i].toString()
return ans
def toString(self):
return '%s' % self.toDict()
#-----------------------------------------------------------------------
class Page():
'''
'''
def __init__(self):
self.records = Records()
def toString(self):
return self.records.toString()
#-----------------------------------------------------------------------
class Papers():
'''
'''
def __init__(self):
self.f_papers = {}
def __getitem__(self,key):
if not (self.f_papers.get(key,None)):
self.f_papers[key] = Page()
return self.f_papers[key]
def toString(self):
ans = {}
for i in self.f_papers:
ans[i] = self.f_papers[i].toString()
return '%s' % ans
#-----------------------------------------------------------------------
#tests
a = Papers()
a[1].records[1] = Record('group','red','open', 'group1')
a[1].records[2] = Record('group','green','open', 'group2')
a[2].records[7].title = "ffff"
a[1].records[1].title = 'title :-) '
print a[1].records[1].toString()
print a.toString()
toStringandtoDict?jsonmodule instead of relying ondict.__str__(by the way if you want to return an object with its default string formatting you can just returnstr(self.toDict())). A Python's dict representation looks close-enough to valid JSON most of the time, but there are corner cases that will bite you if you don't use a JSON library.