我写了以下代码来检查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函数来释放它的资源,首先是 main 离开,然后是 A del,最后是 B。
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解释器似乎得到了它拥有的所有对象的dict,当对象离开它的区域时,它会按照dict序列释放它的资源,这可能和alph序列一样,这是真的吗?