Accessing dict keys like an attribute?

前端 未结 27 2814
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:04

    From This other SO question there's a great implementation example that simplifies your existing code. How about:

    class AttributeDict(dict):
        __slots__ = () 
        __getattr__ = dict.__getitem__
        __setattr__ = dict.__setitem__
    

    Much more concise and doesn't leave any room for extra cruft getting into your __getattr__ and __setattr__ functions in the future.

提交回复
热议问题