python - 在Python中设置嵌套字典: Why class method behaves differently from an standalone function?

标签 python dictionary

考虑这个简化的类:

class test(object):

    def __init__(self):
        self.inner_dict = {}

    def nested_set_method(self, keys,value=None):
        end = len(keys) - 1
        for index, component in enumerate(keys):
            if index < end or value is None:
                self.inner_dict = self.inner_dict.setdefault(component, {})
            else:
                self.inner_dict[component] = value

这个函数与上面类的nested_set_method相同:

def nested_set_standalone(input_dict, keys,value=None):
    end = len(keys) - 1
    for index, component in enumerate(keys):
        if index < end or value is None:
            input_dict = input_dict.setdefault(component, {})
        else:
            input_dict[component] = value

这是该类的示例用法:

>>> a = test()
>>> a.inner_dict
{}
>>> a.nested_set_method([1,2,3,4],'l')
>>> a.inner_dict
{4: 'l'}

这是该函数在类实例上的示例用法:

>>> b = test()
>>> b.inner_dict
{}
>>> nested_set_standalone(b.inner_dict,[1,2,3,4],'l')
>>> b.inner_dict
{1: {2: {3: {4: 'l'}}}}

我期望该类的 nested_set_method 具有此输出 {4: 'l'} 与函数 nested_set_standalone 具有相同的输出,即{1: {2: {3: {4: 'l'}}}}

但是为什么它们不同呢?

编辑:我在 Python 3.6.6 上运行了这些示例

最佳答案

inner_dict 在函数中是一个局部变量,但在方法中它改变了属性。简单地说,也使用局部变量:

class test(object):
    def __init__(self):
        self.inner_dict = {}

    def get_nested_dict(self, keys):
        inner_dict = self.inner_dict
        for component in keys:
            inner_dict = inner_dict.setdefault(component, {})
        return inner_dict

    def nested_set_method(self, keys,value=None):
        if value is None:
            return self.get_nested_dict(keys)
        else:
            inner_dict = self.get_nested_dict(keys[:-1])
            inner_dict[keys[-1]] = value

关于python - 在Python中设置嵌套字典: Why class method behaves differently from an standalone function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054286/

相关文章:

python - 为什么不将工作替换为以元组为键的字典?

swift - Dictionary 类型的计算属性的 Setter

python - concurrent.futures 是 GIL 的良药吗?

python - 如何将类似字符串的字节转换为普通字节?

python - 在另一个数组中的位置映射 numpy 数组和求和值

python - 正在寻找函数语法来根据两个不同的字典键/值对检查数据帧列?

c - 仅映射文件 C 的第一个字母

arrays - 如何创建一个数组或字典,其值只能是 String、Int 和 Boolean?

python - 使用discord.py,有什么方法可以让我的discord 机器人在成员选项卡的 'playing' 部分显示自定义消息?

python - 在条形图中使用 yerr 以及将数据透视表与 Pandas 一起使用时出现 ValueError