How to change behavior of dict() for an instance

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

    You need to override __iter__.

    def __iter__(self): 
        return iter((k, (v.dictify() if isinstance(v, dict) else v)) 
                    for (k, v) in self.items())
    

    Instead of self.items(), you should use self.iteritems() on Python 2.

    Edit: OK, This seems to be your problem:

    >>> class B(dict): __iter__ = lambda self: iter(((1, 2), (3, 4)))
    ... 
    >>> b = B()
    >>> dict(b)
    {}
    >>> class B(list): __iter__ = lambda self: iter(((1, 2), (3, 4)))
    ... 
    >>> b = B()
    >>> dict(b)
    {1: 2, 3: 4}
    

    So this method doesn't work if the object you're calling dict() on is a subclass of dict.

    Edit 2: To be clear, defaultdict is a subclass of dict. dict(a_defaultdict) is still a no-op.

提交回复
热议问题