【问题标题】:Preempting __del__ hmmm抢占 __del__ 嗯
【发布时间】:2009-10-15 22:52:42
【问题描述】:

我需要抢占__del__,我想知道什么是正确的方法。基本上我的代码问题是这样的..

class A:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("In init")
        self.closed = False

    def close(self):
        self.log.debug("Doing some magic")
        self.closed = True

    def __del__(self):
        if not self.closed:
            self.close()
        self.log.debug("In closing")

        # What should go here to properly do GC??

现在有什么方法可以调用标准的 GC 功能吗?

感谢阅读!!

史蒂夫

【问题讨论】:

  • 抢占?为什么?你到底想达到什么目的?

标签: python class


【解决方案1】:

__del__ 不是真正的析构函数。在对象被销毁之前调用它以释放它所持有的任何资源。它不必担心释放内存本身。

如果您继承的类也可能具有开放资源,您也可以随时调用父类'__del__

【讨论】:

    【解决方案2】:

    请为此使用with 声明。

    http://docs.python.org/reference/compound_stmts.html#the-with-statement

    with 语句保证如果 enter() 方法返回没有 一个错误,然后 exit() 将始终 被调用。

    与其玩弄__del__,不如使用上下文管理器对象的__exit__

    【讨论】:

    • @rh0dium:你读过 with 语句和上下文管理器吗?你有什么问题?
    • 只有在你知道你的代码不会被 Python 2.5 之前的版本使用时才使用 with 语句。
    【解决方案3】:

    如果您希望手动调用 GC,请调用 gc.collect()。

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 2020-11-09
      • 2011-11-23
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2020-05-13
      • 2013-02-22
      相关资源
      最近更新 更多