To aid in serializing to JSON, I commonly build a class that inherits from the python dict class. If the class is supposed to have specific fields, I want there to be methods to get & set.
Currently, I construct a class like:
class MyRequest(dict):
def __init__(self, firstName=None, lastName=None):
self['firstName'] = firstName
self['lastName'] = lastName
def get_firstName(self):
return self['firstName']
def set_firstName(self, firstName):
self['firstName'] = firstName
def get_lastName(self):
return self['lastName']
def set_lastName(self, lastName):
self['lastName'] = lastName
But this is really cumbersome to work with. Since the underlying ‘storage’ is a dictionary, I can’t just access fields like
myReq.firstName = "Foo"
print myReq.lastName
But is there a way to get to there while still keeping the dict backing?
Yes, there is a way to do what you want. Use properties: