为了帮助序列化为JSON,我通常构建一个继承自python dict类的类。如果该类应该具有特定的字段,我希望有方法来获取&集。
目前,我构建了一个类:
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
但这真的很麻烦。由于底层的“存储”是一个字典,我不能只访问像
这样的字段myReq.firstName = "Foo"
print myReq.lastName
但是有没有办法到达那里,同时仍然保持dict支持?
答案 0 :(得分:2)
怎么样:
class MyRequest(dict):
def __init__(self, firstName=None, lastName=None):
self['firstName'] = firstName
self['lastName'] = lastName
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
请注意,如果您的某个属性与dict
方法具有相同的名称(例如update
),则可能会再次困扰您。在这种情况下,获取属性将返回该方法,设置它将覆盖该方法。这可能很难调试。
答案 1 :(得分:1)
是的,有办法做你想做的事。使用属性:
class MyRequest(dict):
def __init__(self, firstName=None, lastName=None):
self['firstName'] = firstName
self['lastName'] = lastName
@property
def firstName(self):
return self['firstName']
@firstName.setter
def firstName(self, firstName):
self['firstName'] = firstName
@property
def lastName(self):
return self['lastName']
@lastName.setter
def lastName(self, lastName):
self['lastName'] = lastName
request = MyRequest('John', 'Connor')
print request.firstName, request.lastName
request.firstName = 'Sarah'
print request.firstName, request.lastName