Skip to main content
 首页 » 编程设计

python之Python中的类实例删除

2025年05月04日10EasonJim

有没有办法让一个类删除它自己的一个实例。我知道你可以为变量做 del x 但你如何为类做那件事?如果我做类似的事情:

class foo(object): 
    x=5 
    def __init__(self): 
        print "hi" 
    def __del__(self): 
        del self 
        print "bye" 
 
a = foo() 
a.__del__() 
print a.x 

代码的输出是

hi 
bye 
5 

foo 的实例没有被删除。有没有办法让类(class)做到这一点?

请您参考如下方法:

不,如果您有一个类实例的引用,那么根据定义它还有剩余的引用。您可以使用 del 关键字删除名称(释放该名称对对象的引用),但如果对该实例的引用保存在别处,则该实例将保留。

如果您想要的是确定性清理行为,请不要使用 __del__(这在明显或一致的方式上不是确定性的,并且在 Python 3.4 之前,可能会导致引用循环泄漏如果循环的任何成员是定义了 __del__ 终结器的类的实例)。让类实现 the context manager protocol ,并使用带有 with 语句的实例来进行确定性清理;该实例将仍然存在,直到最后一个引用消失,但只要 __exit__ 执行必要的资源释放,实例的空壳几乎不会花费您任何费用。

作为上下文管理的一个例子,我们将使x成为foo的实例属性,而不是类属性,我们会说我们需要确保实例的对 x 的引用在已知时间消失(注意,因为 del 只是删除了我们的引用,如果其他人保存了 a.x,则该对象将丢失在其他引用也被释放之前实际上被释放:

class foo(object): 
    def __init__(self, x): 
        self.x = x 
        print "hi" 
    def __enter__(self): 
        return self 
    def __exit__(self, exc_type, exc_val, exc_tb): 
        print "bye" 
        del self.x 
 
with foo(123456789) as a: 
    print a.x  # This works, because a.x still exists 
# bye is printed at this point 
print a.x # This fails, because we deleted the x attribute in __exit__ and the with is done 
# a still exists until it goes out of scope, but it's logically "dead" and empty