Python 2.7-如何使用函数删除字典?
我在Python 2.7.5.6中有以下函数:Python 2.7-如何使用函数删除字典?,python,Python,我在Python 2.7.5.6中有以下函数: """ Delete entire *existing* store from memory. Prior to doing so, a backup copy of the store is saved to disk with the current date and time as part of the filename: """ def drop(store): backup(store) del store ##
"""
Delete entire *existing* store from memory. Prior to doing so, a backup
copy of the store is saved to disk with the current date and time as
part of the filename:
"""
def drop(store):
backup(store)
del store
## BUGGY: the store is preserved in its entirety
其中
store
是一本字典。如果我在pythonshell(IDLE)中发出上述函数体中的每个命令,就会得到所需的行为。但是,调用函数drop()
不起作用;存储
字典不会被删除并保留。任何帮助都将不胜感激 这是因为您只需删除作为参数传入的字典存储的本地副本。如果要删除原始词典,只需在代码中调用del(store)
方法,实际需要删除store
,如下所示:
def drop(store):
backup(store)
store = {}
drop(store)
del store
你也可以这样做
def drop(local_store):
global store
backup(local_store)
del store
store = {}
drop(store)
您可以使存储区成为包含字典的对象;这将允许您从函数中删除它:
class Store:
def __init__(self, data=None):
self.data = data or {}
def clear(self):
backup(self.data)
self.data = {}
store = Store()
def drop(store):
store.clear()
我希望在所说的函数中,有一个函数能够删除实际的存储
字典,而不是作为函数参数传递的它的副本。我还有其他功能,比如insert(store,value)
,在本例中,它在实际的store
中插入一条新记录。下面是insert(store,value)
(有效):“insert(作为下一个键追加)新记录到*现有*存储:”“def insert(store,value):key=nextID(store)store[key]=value print“Inserted record”+key+“:”,store[key]print return
有什么灵魂可以告诉我为什么insert(store,value)
——一个自包含的函数可以工作,而我原来版本的drop(store)
并没有删除实际的store
?对不起,我找不到一种方法来正确格式化(使用缩进)我的insert(store,value)
示例代码。有什么提示吗?