How to change behavior of dict() for an instance

前端 未结 6 1265
悲哀的现实
悲哀的现实 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:21

    Nothing wrong with your approach, but this is similar to the Autovivification feature of Perl, which has been implemented in Python in this question. Props to @nosklo for this.

    class RecursiveDict(dict):
        """Implementation of perl's autovivification feature."""
        def __getitem__(self, item):
            try:
                return dict.__getitem__(self, item)
            except KeyError:
                value = self[item] = type(self)()
                return value
    
    >>> a = RecursiveDict()
    >>> a[1][2][3] = 4
    >>> dict(a)
    {1: {2: {3: 4}}}
    

    EDIT

    As suggested by @Rosh Oxymoron, using __missing__ results in a more concise implementation. Requires Python >= 2.5

    class RecursiveDict(dict):
        """Implementation of perl's autovivification feature."""
        def __missing__(self, key):
            value = self[key] = type(self)()
            return value
    

提交回复
热议问题