发生break语句时生成器被破坏

2024-10-01 07:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道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()退出循环之前。在

当循环留给生成器中定义的对象的方法时,我可以依赖于此并给出一些我想完成的任务吗?在


Tags: 方法integerstestobjformydeffunction
3条回答

I want to know when the Obj.__del__() method is going to be called.

你不能。可能永远不会。Python中的终结器(或者在任何具有自动垃圾收集器方案的环境中)根本不能保证运行,只能用于最后的清理。如果您想要可预测的生命周期管理,请使用^{} statementcontext managers。在

class Foo(object):
    def __enter__(self):
        print 'Entered with block'
    def __exit__(self, *exc_info):
        print 'Exited with block'
        return False

with Foo():
    pass

一般来说,你不能依赖析构函数调用顺序。在垃圾回收器回收对象时调用析构函数。这可能在不确定的将来发生,或者如果您的程序因异常而死亡,则根本不会发生。在

如果您想要对象的确定生命周期,请考虑creating it inside a ^{}-decorated function并使用with语句。在

下面是Python语言引用对^{}的描述

x.__del__() — ... is only called when x‘s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects; a reference to the object on the stack frame of a function that caught an exception ...

因此,您不应该依赖__del__进行清理。上下文管理器(作为catplusmentions above)是正确的选择。在

相关问题 更多 >