gpt4 book ai didi

python - 为什么我无法获得预期输出 'BBB' ?

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:34 25 4
gpt4 key购买 nike

# -*- coding: utf-8 -*-
class tA():
def __init__(self):
print 'AAA'

def __del__(self):
print 'BBB'

class tC(tA):
def __init__(self, a, b=0):
tA.__init__(self)
self.b=b # 1. del this ok

class tD(tC):
def __init__(self):
a=1
#tC.__init__(self, a) # 2. use this ok
tC.__init__(self, a, self.func) # 3. use this not ok
#tC.__init__(self, a, 3) # 4. use this ok

def func(self, pos):
pass
if __name__ == '__main__':
tD()

为什么没有'BBB'输出?

如果我删除 #1 ,输出就可以了

如果我使用#2 或#4,输出就可以了

如果我使用#3,输出没有'BBB'?

最佳答案

因为你的 'BBB' 是用你的类的终结器打印的(__del__ 函数)。终结器在垃圾收集器收集您的对象时运行。

Python 使用双重策略进行垃圾回收:引用计数和循环检测。引用计数为 0 的对象会立即被收集,但如果它们参与循环,则它们的计数永远不会为 0。然后周期性调用的 GC 循环检测例程最终会检测到并释放所有悬挂对象。

在您的特定代码中,案例 #3 创建了一个引用循环:self.b 是对 self.func 的引用。但是 GC 循环检测永远不会运行,因为程序在它有任何机会之前就结束了。

但是即使运行了GC,带有终结器的对象也有特殊的规则。来自documentation :

Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the __del__() methods.

此外,来自 here

Changed in version 3.4: Following PEP 442, objects with a __del__() method don’t end up in gc.garbage anymore.

所以,看起来,在 Python 3.4 之前的版本中,在带有终结器的类中,您必须手动中断循环:

If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list. Note that these objects are kept alive even so by virtue of being in the garbage list, so they should be removed from garbage too. For example, after breaking cycles, do del gc.garbage[:] to empty the list.

关于python - 为什么我无法获得预期输出 'BBB' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com