gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:51:54 25 4
gpt4 key购买 nike

考虑这个简化的类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com