编程语言
首页 > 编程语言> > 基于try / finally yield的Python析构函数?

基于try / finally yield的Python析构函数?

作者:互联网

我一直在测试受此http://docs.python.org/2/library/contextlib.html启发的肮脏黑客.
主要思想是将try / final思想带到类级别,并获得可靠且简单的类析构函数.

class Foo():
  def __init__(self):
    self.__res_mgr__ = self.__acquire_resources__()
    self.__res_mgr__.next()

  def __acquire_resources__(self):
    try:
      # Acquire some resources here
      print "Initialize"
      self.f = 1
      yield
    finally:
      # Release the resources here
      print "Releasing Resources"
      self.f = 0

f = Foo()
print "testing resources"
print f.f

但这总是给我:

Initialize
testing resources
1

永远不要“释放资源”.我将希望寄托在:

As of Python version 2.5, the yield statement is now allowed in the
try clause of a try … finally construct. If the generator is not
resumed before it is finalized (by reaching a zero reference count or
by being garbage collected), the generator-iterator’s close() method
will be called, allowing any pending finally clauses to execute. 07001

但是似乎在将类成员与类一起进行垃圾回收时,其引用计数不会减少,因此结果是生成器close()并因此最终从未被调用.至于报价的第二部分

“or by being garbage collected”

我只是不知道为什么这不是真的.有机会让这个乌托邦发挥作用吗?

标签:destructor,generator,yield,python,garbage-collection
来源: https://codeday.me/bug/20191122/2057931.html