How to change behavior of dict() for an instance

前端 未结 6 1312
悲哀的现实
悲哀的现实 2021-01-30 09:21

So I\'m writing a class that extends a dictionary which right now uses a method \"dictify\" to transform itself into a dict. What I would like to do instead though is change it

6条回答
  •  攒了一身酷
    2021-01-30 10:12

    Do you want just to print it like a dict ? use this:

    from collections import defaultdict
    
    class RecursiveDict(defaultdict):
        '''
        A recursive default dict.
    
        >>> a = RecursiveDict()
        >>> a[1][2][3] = 4
        >>> a.dictify()
        {1: {2: {3: 4}}}
        >>> dict(a)
        {1: {2: {3: 4}}}
    
        '''
        def __init__(self):
            super(RecursiveDict, self).__init__(RecursiveDict)
    
        def dictify(self):
            '''Get a standard dictionary of the items in the tree.'''
            return dict([(k, (v.dictify() if isinstance(v, dict) else v))
                         for (k, v) in self.items()])
    
        def __dict__(self):
            '''Get a standard dictionary of the items in the tree.'''
            print [(k, v) for (k, v) in self.items()]
            return dict([(k, (dict(v) if isinstance(v, dict) else v))
                         for (k, v) in self.items()])
    
        def __repr__(self):
            return repr(self.dictify())
    

    Maybe you are looking for __missing__ :

    class RecursiveDict(dict):
        '''
        A recursive default dict.
    
        >>> a = RecursiveDict()
        >>> a[1][2][3] = 4
        >>> a
        {1: {2: {3: 4}}}
        >>> dict(a)
        {1: {2: {3: 4}}}
    
        '''
    
        def __missing__(self, key):
            self[key] = self.__class__()
            return self[key]
    

提交回复
热议问题