IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    将 Json 转换为 Python Object(二)

    Yiran\'s Blog发表于 2018-06-17 21:00:49
    love 0
    最近趁着端午假期,终于把 《流畅的 Python》看完了,收获很大,书中某一章节介绍了 addict 库,可以将 Json 转换为 Python Object 。 今天看了看具体的实现方式,比 Stack Overflow 的回答完整,补发一篇博客学习下。 源码代码很少,补充一些关键变量用于了解整体实现流程。 import copy from pprint import pprint class Dict(dict): def __init__(__self, *args, **kwargs): print 'init kwargs is ', kwargs object.__setattr__(__self, '__parent', kwargs.pop('__parent', None)) object.__setattr__(__self, '__key', kwargs.pop('__key', None)) for arg in args: if not arg: continue elif isinstance(arg, dict): for key, val in arg.items(): __self[key] = __self._hook(val) elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)): __self[arg[0]] = __self._hook(arg[1]) else: for key, val in iter(arg): __self[key] = __self.


沪ICP备19023445号-2号
友情链接