考虑这个简化的类:
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上运行了这些示例
答案 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