python - 使用 python 3.5,相同的代码在不同的电脑上有不同的输出

标签 python python-3.x

我有这个代码:

import gc

def hacerciclo():
    l=[0]
    l[0]=l

recolector=gc.collect()
print("Garbage collector %d" % recolector)
for i in range (10):
    hacerciclo()

recolector=gc.collect()
print("Garbage collector %d" % recolector)

这是使用 gc.collect() 的示例代码。问题是相同的代码在不同的计算机上显示不同的输出。

一台电脑显示: 垃圾收集器1 垃圾收集器10 其他显示: 垃圾收集器 0 垃圾收集器10

为什么会发生这种情况?

最佳答案

The current version of Python uses reference counting to keep track of allocated memory. Each object in Python has a reference count which indicates how many objects are pointing to it. When this reference count reaches zero the object is freed. This works well for most programs. However, there is one fundamental flaw with reference counting and it is due to something called reference cycles. The simplest example of a reference cycle is one object that refers to itself. For example:

>>> l = []
>>> l.append(l)
>>> del l

The reference count for the list created is now one. However, since it cannot not be reached from inside Python and cannot possibly be used again, it should be considered garbage. In the current version of Python, this list will never be freed.

Creating reference cycles is usually not good programming practice and can almost always be avoided. However, sometimes it is difficult to avoid creating reference cycles and other times the programmer does not even realize it is happening. For long running programs such as servers this is especially troublesome. People do not want their servers to run out of memory because reference counting failed to free unreachable objects. For large programs it is difficult to find how reference cycles are being created.

来源:http://arctrix.com/nas/python/gc/

下面的链接包含您正在使用的示例,并且还进行了说明:

http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection

关于python - 使用 python 3.5,相同的代码在不同的电脑上有不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027392/

相关文章:

python - 将列表项分发给python中的变量

python - 限制 Azure 机器学习管道使用的节点数量

python - tkinter 通过 VNC 无需物理显示

python - 如何将 matplotlib 绘图保存为 .png 文件

python - 将 2D numpy 数组排序到每个元素与某个点的接近度

python 文件操作

python - 将可变数量的参数从 Python 传递到 mysql

python-3.x - 如何从 pd.Dataframe 中提取索引

Python decimal.InvalidOperation 错误

Python 在并行处理大文件时不释放 RAM