[英]Null a dictionary inside a function in python
我不太確定以下原因為何不起作用。 我嘗試將字典對象發送給函數,測試一些東西,如果滿足某些條件,則使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 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,但是由於某些原因,無法將其設置為None。 為什么是這樣? 這種看似不一致的行為是否有充分的理由? 原諒我的無知,我在python上讀過的書都沒有解釋這一點。 據我了解,字典是“可變的”,該函數應使字典對象為空,而不是它的某些副本。
我知道我可以通過設置b = destroy(b)並從destroy()返回None來解決它,但是我不明白為什么上面的方法不起作用。
當你說
a = None
你正在a
指None
,這是較早指着字典對象。 但是當你這樣做
a['car'] = 9
a
仍然是對字典對象的引用,因此,您實際上只是在向字典對象添加新的鑰匙car
。 這就是為什么它起作用。
因此,清除字典的正確方法是使用dict.clear
方法,如下所示
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]
你不破壞任何東西,你只是改變a
的值None
在destroy
的局部范圍。
為什么不簡單地使用:
some_dictionary = None
要刪除對some_dictionary
引用? 當沒有人再引用some_dictionary
時,垃圾收集器將進行銷毀。
在您的代碼中:
b = None # replaced: destroy(b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.