推荐学习书目
› 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 · Nov 4, 2016 · 2607 views
    This topic created in 3618 days ago, the information mentioned may be changed or developed.

    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 replies  •  2016-11-04 16:21:42 +08:00
    petelin
        1
    petelin  
    OP
       Nov 4, 2016
    通过调用站找到是否是**调用 dict,然后把 keys 给干掉了...总觉得会有 bug.

    https://gist.github.com/Petelin/5b378c1aec8b43eccb72ff13a785e473
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2336 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 07:30 · PVG 15:30 · LAX 00:30 · JFK 03:30
    ♥ Do have faith in what you're doing.