gpt4 book ai didi

python - 如何将对象交给 python 垃圾回收?

转载 作者:太空狗 更新时间:2023-10-29 18:18:50 25 4
gpt4 key购买 nike

在 SO 中有几个关于 Python 垃圾收集的线程,在阅读了大约五个线程以及一些在线文档之后,我仍然不确定垃圾收集是如何工作的以及我应该如何管理我不使用的对象。事实上,我在某处读到一个人不应该做任何关于收集垃圾的事情,其他人告诉一个人应该 del 对象,而其他人再次解释取消引用一个对象足以让 Python 将它作为垃圾收集。

因此,冒着重复的风险,我会再次提出这个问题,但有所不同,希望获得更全面、更清晰的信息。

在我的例子中,我想用代表人的物体做一个小的模拟。 Person() 类的多个实例将被创建。它应该存在一段时间,直到它实际上“死亡”,而其他实例将被创建。

现在我如何让这个 Person() 实例“消亡”(假设将创建许多这样的实例并且我不希望这些实例像幽灵一样闲逛)?

有几种方法可以引用一个对象:

john = Person('john')

people = []
people.append(Person('john'))

people = {}
people['john'] = Person('john')

什么是保持我的程序干净、以最佳方式释放资源的最佳方法?那么引用我的对象以便我可以控制对象的删除的最佳方法是什么?

最佳答案

也许这也可以帮助:

>>> # Create a simple object with a verbose __del__ to track gc.
>>> class C:
... def __del__(self):
... print "delete object"
...
>>> c = C()
>>> # Delete the object c successfully.
>>> del c
delete object
>>> # Deletion of an object when it go out of the scope where it was defined.
>>> def f():
... c = C()
...
>>> f()
delete object
>>> c = C()
>>> # Create another reference of the object.
>>> b = c
>>> # The object wasn't destructed the call of del only decremented the object reference.
>>> del c
>>> # Now the reference counter of the object reach 0 so the __del__ was called.
>>> del b
delete object
>>> # Create now a list that hold all the objects.
>>> l = [C(), C()]
>>> del l
delete object
delete object
>>> # Create an object that have a cyclic reference.
>>> class C:
... def __init__(self):
... self.x = self
... def __del__(self):
... print "delete object"
...
>>> c = C()
>>> # Run the garbage collector to collect object.
>>> gc.collect()
9
>>> # the gc.garbage contain object that the gc found unreachable and could not be freed.
>>> gc.garbage
[<__main__.C instance at 0x7ff588d84368>]
>>> # Break the cyclic reference.
>>> c.x = None
>>> # And now we can collect this object.
>>> del c
delete object
>>> # Create another object with cyclic reference.
>>> c = C()
>>> # When closing the interactive python interpreter the object will be collected.
delete object

引用文献:del method ; gc module ; weakref module

关于python - 如何将对象交给 python 垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6315244/

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