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()
您可以使用decorator来“标记”需要表示的属性。 您仍然需要编写一个to_json函数,但只需在基类中定义一次
下面是一个简单的例子:
印刷品
^{pr2}$相关问题 更多 >
编程相关推荐