python - 如何为实例更改 dict() 的行为

标签 python dictionary overriding autovivification

所以我正在编写一个扩展字典的类,该字典现在使用“dictify”方法将自身转换为字典。我想做的是改变它,以便在对象上调用 dict() 导致相同的行为,但我不知道要覆盖哪个方法。这是不可能的,还是我错过了一些非常明显的东西? (是的,我知道下面的代码不起作用,但我希望它说明了我正在尝试做的事情。)

from collections import defaultdict

class RecursiveDict(defaultdict):
    '''
    A recursive default dict.

    >>> a = RecursiveDict()
    >>> a[1][2][3] = 4
    >>> a.dictify()
    {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()])

编辑:为了更清楚地显示问题:

>>> b = RecursiveDict()
>>> b[1][2][3] = 4
>>> b
defaultdict(<class '__main__.RecursiveDict'>, {1: defaultdict(<class '__main__.RecursiveDict'>, {2: defaultdict(<class '__main__.RecursiveDict'>, {3: 4})})})
>>> dict(b)
{1: defaultdict(<class '__main__.RecursiveDict'>, {2: defaultdict(<class '__main__.RecursiveDict'>, {3: 4})})}
>>> b.dictify()
{1: {2: {3: 4}}}

我希望 dict(b) 和 b.dictify() 一样

最佳答案

您的方法没有问题,但这类似于 Perl 的 Autovivification 功能,该功能已在 Python in this question 中实现.为此向@nosklo 提供 Prop 。

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}}}

编辑

正如@Rosh Oxymoron 所建议的,使用 __missing__ 可以实现更简洁的实现。需要 Python >= 2.5

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

关于python - 如何为实例更改 dict() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780952/

相关文章:

python - 无法将关键字 'i' 解析为字段。选择是 : id, joined_on, user, user_id

java - Java/Python 中的快速 IPC/Socket 通信

javascript - JavaScript 中的 "method overloading"

java - 覆盖从构造函数调用的方法

c++ - 如何用参数重载 '=' 运算符?

python - 这可以用 django __str__ 方法来完成吗?

python - 在单元测试中将 errno 与 assertRaises 结合使用

java - 自定义 equals() 方法无法正常工作

python - 在python中,如何订购带有unicode内容的字典?

python - 更新 python 中字典列表的值