您可以使用decorator来“标记”需要表示的属性。
您仍然需要编写一个to_json函数,但只需在基类中定义一次
下面是一个简单的例子:import json
import inspect
def viewable(fnc):
'''
Decorator, mark a function as viewable and gather some metadata in the process
'''
def call(*pargs, **kwargs):
return fnc(*pargs, **kwargs)
# Mark the function as viewable
call.is_viewable = True
return call
class BaseJsonable(object):
def to_json(self):
result = {}
for name, member in inspect.getmembers(self):
if getattr(member, 'is_viewable', False):
value = member()
result[name] = getattr(value, 'to_json', value.__str__)()
return json.dumps(result)
class Person(BaseJsonable):
@viewable
def name(self):
return self._name
@viewable
def surname(self):
return self._surname
def __init__(self, name, surname):
self._name = name
self._surname = surname
p = Person('hello', 'world')
print p.to_json()
印刷品
^{pr2}$
本文介绍了一种利用Python装饰器(decorator)简化对象转JSON的方法。通过定义一个通用的to_json函数,并使用装饰器标记需要序列化的属性,实现了基类及派生类对象的轻松JSON化。

被折叠的 条评论
为什么被折叠?



