重构:统一输出 在项目中,统一返回的入口和出口非常重要。因为你永远没办法知道产品经理下个版本要在返回结果中加什么乱七八糟的东西。 对item的修改,最好抽象成一个组合。用插件的方式进行修改。(有点像commands模式) 首先,创建一个基友类: ``` class BaseResp(object): # 返回结果的基类 def __init__(self, result): self.result = result self.modifiers = [] def add_modifier(self, modifier, args): self.modifiers.append([modifier, args]) def run_modifer(self): for item in self.result: for modifer in self.modifiers: print(modifer) modifer[0](item, modifer[1]) ``` 子类从基友那里派生出来,这样可以预定义行为。 ``` import baseresp class ArticleResp(baseresp.BaseResp): def __init__(self, result): baseresp.BaseResp.__init__(self, result) self.add_modifier(add_gif, None) def add_gif(item, args): is_gif = 0 for pic in item['data']['imgs']: if pic['type'] == 'gif': is_gif = 1 item['data']['Gif'] = is_gif ``` 对所有article的数据,检查是否为gif类型,加上gif标签。 这个行为是预定义行为,将会在所有的article中显现。 测试一下: ``` import article_resp result = [ { 'types': 'article', 'data':{ 'name': 'hello', 'imgs':[ { 'type': 'jpeg', 'name': 'azdes.jpg' }, { 'type': 'jpeg', 'name': 'hello.jpg' }, ] } }, { 'types': 'article', 'data':{ 'name': 'world', 'imgs':[ { 'type': 'gif', 'name': '1azdes.gif' }, { 'type': 'jpeg', 'name': '3hello.jpg' }, ] } } ] article_resp = article_resp.ArticleResp(result) article_resp.run_modifer() print(result) ``` 代码很简单,但带来的效果是巨大的。不这样做的代价是惨重的。 来自 大脸猫 写于 2017-12-03 20:14 -- 更新于2020-10-19 13:06 -- 0 条评论