我编写了以下代码来检查python如何释放它的对象内存,好吧,我发现了一些有趣的东西,但我不确定,所以我在这里发帖请求帮助。
首先
class A():
def __del__(self):
print "A __del__"
class B():
def __del__(self):
print "B __del__"
if __name__ == "__main__":
a = A()
b = B()
print "main leaving"
输出是:
main leaving
A __del__
B __del__
当对象离开其区域时,它会调用 del 函数释放其资源,第一个主要假,然后是A del ,最后一个B. / p>
I thought may be A & B's __del__ function call's sequence is influenced by the object declare sequence, so I write it like this:
class A():
def __del__(self):
print "A __del__"
class B():
def __del__(self):
print "B __del__"
if __name__ == "__main__":
b = B() ### declare b first
a = A()
print "main leaving"
嗯,输出相同。
然后我重写代码
class B():
def __del__(self):
print "B __del__"
class A():
def __del__(self):
print "A __del__"
if __name__ == "__main__":
a = A()
b = B()
print "main leaving"
然而,结果是一样的。
所以,似乎python解释器得到了它拥有的所有对象的字典,当对象离开它的区域时,它将通过字典序列释放其资源,这可能与alph序列相同,是这是真的吗?
答案 0 :(得分:1)
GC似乎会按字母顺序删除变种。
class A(object):
def __init__(self, val):
self.val = val
def __del__(self):
print self.val
if __name__ == '__main__':
b = A(2)
a = A(1)
c = A(3)
d = A(4)
print 'Bye!'
Bye!
1
3
2
4
但它并不总是奏效。
class A(object):
def __init__(self, val):
self.val = val
def __del__(self):
print self.val
if __name__ == '__main__':
b = A(2)
a = A(1)
d = A(4)
c = A(3)
print 'Bye!'
Bye!
1
3
2
4