在Python中设置嵌套字典:为什么类方法的行为与独立函数不同?

时间:2018-10-29 21:44:02

标签: 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上运行了这些示例

1 个答案:

答案 0 :(得分:1)

函数中的

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