Python是否会自动清除对象? [英] Does Python automatically clear up objects?

查看:73
本文介绍了Python是否会自动清除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

populationList = []
for i in range(0, 2000)
    populationList.append(myObject).

populationList = []

现在已经删除了对总人口清单中所有对象的引用吗?我了解Java就是这种情况,但Python是否一样?还是应该显式删除对象?

Would all the objects within populationList get cleaned up now the reference to them has been deleated? I understand that this is the case in Java but it it the same for Python? Or should the objects need to be explicitly deleated?

推荐答案

CPython使用引用计数自动清除不再引用的对象.

CPython uses reference counting to automatically clean up objects that are no longer referenced.

每个名称,列表索引,字典值或键条目或属性都是对Python对象的引用,并且解释器根据需要递增和递减每个对象的引用计数.当计数达到0时,对象将自动从内存中清除.

Each name, list index, dictionary value or key entry, or attribute is a reference to a Python object, and the interpreter increments and decrements the reference count on each object as needed. When the count reaches 0, objects are automatically cleared from memory.

populationList重新绑定到 new 列表对象时,旧列表的引用计数下降为0,并被清除.依次清除所有对包含对象的引用,也将其清除,等等.

When you rebind populationList to a new list object, the reference count for the old list drops to 0 and it is cleared. That in turn clears all references to the contained objects, and they are cleared too, etc.

垃圾收集器进程还跟踪循环引用(仅相互​​引用的对象),并根据需要自动中断此类循环.请参阅 gc模块中的工具,以进行内部检查和更改其行为.垃圾收集器.

A garbage collector process also tracks circular references (objects that only reference one another), breaking such cycles automatically as needed. See the gc module for a tool to introspect and alter the behaviour of the garbage collector.

您可以通过实现 <您的自定义类上的c2>方法.请阅读文档以了解此挂钩的限制.

You can hook into the object de-allocation process by implementing a __del__ method on your custom class. Do read the documentation to learn about the limitations to this hook.

快速演示:

>>> class Foo:
...     def __init__(self, x):
...         self.x = x
...     def __del__(self):
...         print(self.x, 'deleted')
... 
>>> populationList = []
>>> for i in range(5):
...     populationList.append(Foo(i))
... 
>>> populationList = []
4 deleted
3 deleted
2 deleted
1 deleted
0 deleted

Jython和IronPython等其他Python实现使用不同的技术来跟踪可以清除的对象.

Other Python implementations such as Jython and IronPython use different techniques to track objects that can be cleaned up.

这篇关于Python是否会自动清除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆