我想知道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()
我做了一个测试,Obj似乎在break语句之后被删除:在anything\u function()退出循环之前。在
当循环留给生成器中定义的对象的方法时,我可以依赖于此并给出一些我想完成的任务吗?在
你不能。可能永远不会。Python中的终结器(或者在任何具有自动垃圾收集器方案的环境中)根本不能保证运行,只能用于最后的清理。如果您想要可预测的生命周期管理,请使用^{} statement 和context managers。在
一般来说,你不能依赖析构函数调用顺序。在垃圾回收器回收对象时调用析构函数。这可能在不确定的将来发生,或者如果您的程序因异常而死亡,则根本不会发生。在
如果您想要对象的确定生命周期,请考虑creating it inside a ^{}-decorated function 并使用
with
语句。在下面是Python语言引用对^{} 的描述
因此,您不应该依赖
__del__
进行清理。上下文管理器(作为catplusmentions above)是正确的选择。在相关问题 更多 >
编程相关推荐