代码之家  ›  专栏  ›  技术社区  ›  Igor Serebryany

在finalize类型调用后使python对象不可使用

  •  1
  • Igor Serebryany  · 技术社区  · 16 年前

    我有一个python对象,它在系统上封装了一个敏感而重要的资源。我有一个 cleanup() 安全释放对象使用的各种锁的函数。

    清理() 对象变得不可用。理想情况下,对对象的任何成员函数的任何调用都会引发异常。有没有一种方法不需要检查每个函数中的标志?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Matthew Flaschen    16 年前

    一种方法是简单地将所有实例变量设置为 None

    class Unusable:
        def __init__(self):
            self.alive = True
    
        def notcleanedup(func):
            def operation(self, *args, **kwargs):
                if self.alive:
                    func(self, *args, **kwargs)
                else:
                    raise Exception("Use after cleanup")
    
            return operation
    
        @notcleanedup
        def sensitive(self, a, b):
            print a, b
    
        def cleanup(self):
            self.alive = False
    
    推荐文章