考虑这个简化的类:
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'}}}}。
但它们为什么不同呢?
MYYA
相关分类