Skip to main content
 首页 » 编程设计

python之在 pypy 中清理

2025年05月04日12fff_TT

我一直在寻找在 python 中清理对象的方法。 我目前正在使用 pypy。

我找到了一个网页和一个例子。

首先是一个基本的例子:

class FooType(object): 
    def __init__(self, id): 
        self.id = id 
        print self.id, 'born' 
 
    def __del__(self): 
        print self.id, 'died' 
 
 
ft = FooType(1) 

这应该打印:

1 出生 1人死亡

但它只是打印出来 1个出生

所以我的问题是:如何清理 PyPy 中的所有内容?

请您参考如下方法:

当您需要“清理”以确保在特定时间运行时,请使用 context manager .

class FooType(object): 
    def __init__(self, id): 
        self.id = id 
        print 'born' 
    def __enter__(self): 
        print 'entered' 
        return self 
    def __exit__(self, *exc): 
        print 'exited' 
 
with FooType(1) as ft: 
    pass # do something with ft