试图正确删除一个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