我想知道什么时候Obj.将调用del()方法.
def my_integers():
Obj = ExitObj()
i = 0
while(1):
yield i
i += 1
def test_fun():
for i in my_integers():
if i > 3:
break
anything_function()
test_fun()
Run Code Online (Sandbox Code Playgroud)
我做了一个测试,Obj似乎在break语句之后删除:在anything_function()之前循环.
当循环留给生成器内定义的对象的__ del__方法时,我可以依赖于此并提供一些我想要完成的任务吗?
我想知道何时
Obj.__del__()调用该方法.
你不能.它可能永远不会.Python中的终结器(或者在任何具有自动垃圾收集器方案的环境中)都不能保证完全运行,并且只能用于最后的清理.如果需要可预测的生命周期管理,请使用with语句和上下文管理器.
class Foo(object):
def __enter__(self):
print 'Entered with block'
def __exit__(self, *exc_info):
print 'Exited with block'
return False
with Foo():
pass
Run Code Online (Sandbox Code Playgroud)