我正在使用Python 2.7并尝试拥有一个干净的内存(因为我正在编写一个小型服务器).我面临的问题是,最后一次加注的对象仍然保留在垃圾收集器中(然后在第一次尝试/除之后不调用__ del __).
这是一个小例子:
import gc
class A(object):
def raiser(self):
0/0 # will raise an exception
a = A()
try:
a.raiser()
except:
pass
a = None # should release the object from memory
gc.collect() # just to be sure, but doesn't do anything
print '1. Nbr of instance of A in gc : '
print len([o for o in gc.get_objects() if isinstance(o, A)]) # get 1 but expected 1
try:
0/0
except:
pass
print '2. Nbr of instance of …Run Code Online (Sandbox Code Playgroud)