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
petelin
V2EX  ›  Python

比较满意的 attrdict 实现

  •  
  •   petelin · 2016-11-04 15:50:18 +08:00 · 1976 次点击
    这是一个创建于 2736 天前的主题,其中的信息可能已经有所发展或是发生改变。

    dict 大家都知道,然后我想通过 dict.a 这样访问他的 key.想法很美好,但是实现上都很蹩脚,比如 dict.items 到底算是属性呢还是算方法呢?

    所以我就改写了一下用法是这样的

       arg_post = LazeAttrDict(
            {'a': 2, 'keys': 'kk'},
            {
                'a': {
                    'access': str
                },
                'b': {
                    'default': 'default',
                },
                'items': {
                    'default': [1, 2]
                },
                'values': {
                    'default': 'vvv'
                }
    
            })
        assert arg_post.a == "2"
        assert arg_post.b == "default"
        assert arg_post.items == [1, 2]
        assert arg_post.values == "vvv"
    
        # 访问 dict 方法
        print("items 方法")
        for k, v in arg_post._items():
            print('\t', k, v)
    
        print("keys 方法")
        print("\t", list(arg_post._keys()))
        d = dict(**arg_post)
        print("dict 方法\n\t", d)
    
        print("唯一的 bug")
        print(arg_post.keys)
    

    结果

    items 方法
    	 keys kk
    	 a 2
    	 values vvv
    	 b default
    	 items [1, 2]
    keys 方法
    	 ['keys', 'a', 'values', 'b', 'items']
    dict 方法
    	 {'keys': 'kk', 'b': 'default', 'a': '2', 'items': [1, 2], 'values': 'vvv'}
    唯一的 bug
    <bound method Mapping.keys of <__main__.LazeAttrDict object at 0x101c05c50>>
    

    这个 dict 类第二个参数是用来自动校验参数的,有默认值,和转化类型两种方式.

    要是 keys 那个方法也可以干掉就太完美了.

    1 条回复    2016-11-04 16:21:42 +08:00
    petelin
        1
    petelin  
    OP
       2016-11-04 16:21:42 +08:00
    通过调用站找到是否是**调用 dict,然后把 keys 给干掉了...总觉得会有 bug.

    https://gist.github.com/Petelin/5b378c1aec8b43eccb72ff13a785e473
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2306 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:20 · PVG 11:20 · LAX 20:20 · JFK 23:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.