What is a reference cycle in python?

后端 未结 4 962
灰色年华
灰色年华 2020-12-18 17:57

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

4条回答
  •  失恋的感觉
    2020-12-18 18:35

    >>> aRef = []
    >>> aRef.append(aRef)
    >>> print aRef
    [[...]]
    

    This creates a list object referred by a variable namedaRef. the first element in the list object is a reference to itself. In this case, the del aRef dereference aRef to the list object. However, the reference count of the list object does not decrease to zero and the list object is not garbage collected, since the list object still refers to itself. In this case, the garbage collector in Python will periodically check if such circular references exist and the interpreter will collect them. The following is an example to manually collect the space used by circular referenced objects.

    >>> import gc
    >>> gc.collect()
    0
    >>> del aRef
    >>> gc.collect()
    1
    >>> gc.collect()
    0
    

提交回复
热议问题