Accessing dict keys like an attribute?

前端 未结 27 2525
南笙
南笙 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:09

    You can pull a convenient container class from the standard library:

    from argparse import Namespace
    

    to avoid having to copy around code bits. No standard dictionary access, but easy to get one back if you really want it. The code in argparse is simple,

    class Namespace(_AttributeHolder):
        """Simple object for storing attributes.
    
        Implements equality by attribute names and values, and provides a simple
        string representation.
        """
    
        def __init__(self, **kwargs):
            for name in kwargs:
                setattr(self, name, kwargs[name])
    
        __hash__ = None
    
        def __eq__(self, other):
            return vars(self) == vars(other)
    
        def __ne__(self, other):
            return not (self == other)
    
        def __contains__(self, key):
            return key in self.__dict__
    

提交回复
热议问题