python中函数内的字典为Null
我不太清楚为什么下面的方法不起作用。我尝试向函数发送一个dictionary对象,测试一些东西,如果满足某些条件,则将dict设置为null。我不知道为什么 我尝试做的一个简单版本:python中函数内的字典为Null,python,dictionary,Python,Dictionary,我不太清楚为什么下面的方法不起作用。我尝试向函数发送一个dictionary对象,测试一些东西,如果满足某些条件,则将dict设置为null。我不知道为什么 我尝试做的一个简单版本: 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
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}
dict可以按预期由函数修改,但由于某些原因无法设置为无。为什么会这样?这种看似不一致的行为有什么好的理由吗?请原谅我的无知,我读过的关于python的书都没有解释过这一点。据我所知,dict是“可变的”,函数应该使dict对象为空,而不是它的某个副本
我知道我可以通过设置b=destroy(b)并从destroy()返回None来解决这个问题,但我不明白为什么上面的方法不起作用。当你说
a = None
您正在使a
引用None
,它前面指向dictionary对象。但当你这么做的时候
a['car'] = 9
a
仍然是对dictionary对象的引用,因此,实际上您只是在向dictionary对象添加一个新的keycar
。这就是它起作用的原因
所以,清除字典的正确方法是使用如下方法
a.clear()
为什么它不起作用:
>>> a=[1,2,3,4]
>>> def destroy(a):
... del a # here a is local to destroy only
...
>>> destroy(a)
>>> a
[1, 2, 3, 4]
您没有销毁任何内容,只是在
destroy
的本地范围中将a
的值更改为None
为什么您不简单地使用:
some_dictionary = None
要删除对某个词典的引用?当不再有人引用某个字典时,垃圾收集器将进行销毁
在代码中:
b = None # replaced: destroy(b)
你没有破坏任何东西,你只是把
a
的引用在destroy
的本地范围内更改为None
。我不理解“引用”。我发现指针非常混乱。对于那些不熟悉指针/引用的人来说,有没有什么地方可以清楚地解释python中的引用?@shley:你可能会觉得有用。