今天遇见一个奇怪的问题,在python中,对自定义类型的局部变量竟然不进行垃圾回收
测试代码如下
# encoding=utf-8
from memory_profiler import profile
import gc
import time
class A(object):
def __init__(self, id):
self.id = id
for i in range(100):
setattr(self, "test_%s"%i, i)
@profile
def test():
a = []
for i in xrange(10000):
_a = A(i)
a.append(_a)
@profile
def test1():
test()
gc.collect()
time.sleep(10)
if __name__ == ‘__main__‘:
test1()
结果如下:

在test1中调用test函数,理论上来说,调用完test后,test里的局部变量a应该被释放掉,但实际是没有被释放掉。以上在python2.7 和python3.6中都是一样的结论。
原文:https://www.cnblogs.com/xingkongyihao/p/12452476.html