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

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

问题描述

我已经查看过Python的官方文档,但我似乎无法找到参考周期。任何人都可以澄清它是什么,因为我想了解GC模块。

解决方案

引用循环就是指一个或多个引用对象的对象,这样如果你(几乎)最简单的参考周期是有两个对象 a
$ b

/ code>和 b 表示彼此:

  a.other = b 
b.some_attr = a

天真的垃圾收集器严格遵守对象是否被另一个对象引用。在这种情况下,如果 a b 都没有被别的东西引用,它们仍然互相引用,一个天真的垃圾收集器可能无法回收内存。 (我不知道Python是否可以被引用循环所困住)。编辑:最简单的引用循环是引用自身的对象: / p>

  a = [] 
a.append(a)


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.

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

a.other = b
b.some_attr = a

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.)

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

a = []
a.append(a)

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

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