Accessing dict keys like an attribute?

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

    Just to add some variety to the answer, sci-kit learn has this implemented as a Bunch:

    class Bunch(dict):                                                              
        """ Scikit Learn's container object                                         
    
        Dictionary-like object that exposes its keys as attributes.                 
        >>> b = Bunch(a=1, b=2)                                                     
        >>> b['b']                                                                  
        2                                                                           
        >>> b.b                                                                     
        2                                                                           
        >>> b.c = 6                                                                 
        >>> b['c']                                                                  
        6                                                                           
        """                                                                         
    
        def __init__(self, **kwargs):                                               
            super(Bunch, self).__init__(kwargs)                                     
    
        def __setattr__(self, key, value):                                          
            self[key] = value                                                       
    
        def __dir__(self):                                                          
            return self.keys()                                                      
    
        def __getattr__(self, key):                                                 
            try:                                                                    
                return self[key]                                                    
            except KeyError:                                                        
                raise AttributeError(key)                                           
    
        def __setstate__(self, state):                                              
            pass                       
    

    All you need is to get the setattr and getattr methods - the getattr checks for dict keys and the moves on to checking for actual attributes. The setstaet is a fix for fix for pickling/unpickling "bunches" - if inerested check https://github.com/scikit-learn/scikit-learn/issues/6196

提交回复
热议问题