V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
openroc
V2EX  ›  Python

用 python 做了一个简单 dict 封装成 document,大家帮助 review 一下。:)(修改成 gist)

  •  
  •   openroc · 2014-05-28 15:02:11 +08:00 · 2998 次点击
    这是一个创建于 3613 天前的主题,其中的信息可能已经有所发展或是发生改变。
    主要目的针对dict少写[]和“”,如 a["test"]["aaa"], 可以简化成a.test.aaa

    8 条回复    2014-05-29 13:16:43 +08:00
    openroc
        1
    openroc  
    OP
       2014-05-28 15:04:50 +08:00
    binux
        2
    binux  
       2014-05-28 15:11:14 +08:00
    class Obict(dict):
    ....__getattr__ = dict.__getitem__
    ....__setattr__ = dict.__setitem__
    openroc
        3
    openroc  
    OP
       2014-05-28 15:14:28 +08:00
    @blnux, 要支持list和dict,嵌套。:)
    lifemaxer
        4
    lifemaxer  
       2014-05-28 15:15:16 +08:00
    @binux 又见牛人!上次的“uuid.uuid1()”
    binux
        5
    binux  
       2014-05-28 15:18:36 +08:00   ❤️ 1
    @openroc 嵌套就是 return 的时候 Obict 包一下就完了,list 同理
    而且,建议扩展基础类型的时候从 dict, 或者 UserDict 继承,保证类型兼容性。不然你让 keys, items, values, for loop 怎么办?
    openroc
        6
    openroc  
    OP
       2014-05-28 15:22:25 +08:00
    @binux, 嗯,类型兼容的确没有考虑,谢过。
    clino
        7
    clino  
       2014-05-28 15:54:22 +08:00
    这个有类似的作用:
    https://code.google.com/p/ulipad/source/browse/trunk/modules/dict4ini.py
    不过是用在ini文件上

    d = DictIni('t2.ini', format="%s:%s", hideData=True)
    d.a.a = 'mama'
    d.a.b = 'lubs me!'

    d.b.a = 'i'
    d.b.b = 'lub bosunmi!'

    d.c.a = 'dada'
    d.c.b = 'lubs me too!'
    d.save()
    chuangbo
        8
    chuangbo  
       2014-05-29 13:16:43 +08:00
    赞同 @binux,继承 dict 是必须的。
    web.py 的 Storage 是一个比较完整的实现。
    https://github.com/webpy/webpy/blob/master/web/utils.py#L52
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2478 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:10 · PVG 00:10 · LAX 09:10 · JFK 12:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.