python - python 中函数内的字典为空

标签 python dictionary

我不太确定为什么以下不起作用。我尝试将字典对象发送到函数,测试一些内容,如果满足某些条件,则使字典为空。我不知道为什么。

我尝试做的事情的简单版本:

def destroy_bad_variables(a):
    # test if a is a bad variable, nullify if true
    #del a # doesn't work.
    a = None
    print a # this says its null

def change(a):
    a['car'] = 9


b = {'bar':3, 'foo':8}
print b

change(b)
print "change(b):", b

destroy_bad_variables(b)
print "destroy_bad_variables(b):", b

它产生以下输出:

{'foo': 8, 'bar': 3}
change(b): {'car': 9, 'foo': 8, 'bar': 3}
None
destroy_bad_variables(b): {'car': 9, 'foo': 8, 'bar': 3}

字典可以按预期由函数修改,但由于某种原因它不能设置为 None。为什么是这样?这种看似不一致的行为有什么充分的理由吗?原谅我的无知,我读过的关于Python的书都没有解释这一点。据我了解,字典是“可变的”,该函数应该清空字典对象,而不是它的某些副本。

我知道我可以通过设置 b = destroy(b) 并从 destroy() 返回 None 来解决这个问题,但我不明白为什么上面的方法不起作用。

最佳答案

当你说

a = None

您正在使 a 引用 None,它之前指向字典对象。但当你这样做时

a['car'] = 9

a 仍然是对字典对象的引用,因此,您实际上只是向字典对象添加了一个新的 key car 。这就是它起作用的原因。

所以,清除字典的正确方法是使用 dict.clear方法,像这样

a.clear()

关于python - python 中函数内的字典为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470494/

相关文章:

python - 使用 Python 从图像中提取对象

python - 如何将严格排序的字符串列表转换为字典?

python - 在 Python 中,如何按排序键顺序遍历字典?

python - Firefox 本地存储外部访问

python - 使用 catkin_make 测试触发 python rostest

python - Sublime Text 3 - 清洁粘贴

iphone - 如何在标签中获取 map 注释标题样式/字体

html - 将 HTML5 视频标签内的电影映射到模态

python - 使用 Python 导入 - 将多个 excel 文件导入到数据框中

python - 实现表示 "a list with a title"的类的 pythonic 方法是什么?