【发布时间】:2016-06-30 09:16:43
【问题描述】:
尝试正确删除 Python 对象。我正在创建一个对象,然后应该使用“with”语句将其删除。但是当我在'with'语句关闭后打印出来时......对象仍然存在:
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”将变为未定义。您很少需要这样做。
标签: python with-statement