簡體   English   中英

Python 2.7-如何使用函數刪除字典?

[英]Python 2.7 - How to delete a dictionary using a function?

我在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
    ## BUGGY: the store is preserved in its entirety

其中store是字典。 如果我在Python Shell(IDLE)中在上述函數的主體中發出每個命令,則會得到所需的行為。 但是,調用函數drop()無效。 store字典不會被刪除並保留。 任何幫助將不勝感激!

這是因為您只是刪除作為參數傳入的字典store的本地副本。 如果要刪除原始字典,只需在代碼中調用del(store)方法,實際需要刪除store ,如下所示:

def drop(store):
    backup(store)

store = {}
drop(store)
del 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()

你也可以

def drop(local_store):
    global store
    backup(local_store)
    del store

store = {}   
drop(store)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM