python中的引用循环是什么? [英] What is a reference cycle in python?

查看:30
本文介绍了python中的引用循环是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了 python 的官方文档,但我似乎找不到参考循环是什么.任何人都可以澄清它对我来说是什么,因为我正在尝试理解 GC 模块.提前感谢您的回复.

I have looked in the official documentation for python, but i cannot seem to find what a reference cycle is. Could anyone please clarify what it is for me, as i am trying to understand the GC module. Thank you in advance for your replies.

推荐答案

引用循环仅仅意味着一个或多个对象相互引用,这样如果你在纸上用箭头表示依赖关系,你会看到一个循环.

A reference cycle simply means one or more objects referencing each other, such that if you drew it out on paper with arrows representing the dependencies you would see a cycle.

(几乎)最简单的引用循环是有两个对象 ab 相互引用:

The (almost) simplest reference cycle is having two objects a and b that refer to each other:

a.other = b
b.some_attr = a

天真的垃圾收集器严格按照一个对象是否被另一个对象引用来工作.在这种情况下,如果 ab 都没有被其他任何东西引用,它们仍然会相互引用,并且天真的垃圾收集器可能不会回收内存.(不过,我不知道 Python 是否可以被引用循环捕获.)

Naive garbage collectors work strictly off of whether or not an object is referenced by another object. In this case, if both a and b are not referred to by anything else, they still refer to each other and a naive garbage collector may not reclaim the memory. (I don't know if Python can be trapped by reference cycles or not, though.)

最简单的引用循环是引用自身的对象:

The simplest reference cycle is an object that refers to itself:

a = []
a.append(a)

这篇关于python中的引用循环是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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