試圖正確刪除一個Python對象。我創建了一個對象,然後用'with'語句刪除它。但是,當我做後打印出來的「用」的語句被關閉....對象仍然存在:Python'with'not'刪除對象
class Things(object):
def __init__(self, clothes, food, money):
self.clothes = clothes
self.food = food
self.money = money
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('object deleted')
with Things('socks','food',12) as stuff:
greg = stuff.clothes
print(greg)
print(stuff.clothes)
回報:
socks
object deleted
socks
亞歷克斯泰勒的答案是正確的錢。我想補充一點,因爲Python有自動內存管理(垃圾回收),所以你不必擔心刪除不再使用的對象。因此,您爲此目的使用上下文管理器毫無意義。同樣,名稱爲「stuff」的變量由'with'語句創建,但直到腳本結束時纔會繼續存在,如您所見。如果你有一行'del stuff',那麼名字「stuff」變得不確定。你必須這樣做很少見。 –
[with with statement with available with-block?]定義的變量可能重複(http://stackoverflow.com/questions/6432355/variable-defined-with-with-statement-available-outside-of-with-塊) – 2016-03-15 04:47:45