Understanding the number of references to a class variable

This is an attempt to better understand how the reference count works in Python.

Create a class and create it. The instance instance counter will 1( getrefcountdisplays 2because its own internal structures refer to the class instance, increasing the reference counter to 1):

>>> from sys import getrefcount as grc
>>> class A():
    def __init__(self):
        self.x = 100000


>>> a = A()
>>> grc(a)
2

aThe internal variable xhas 2links:

>>> grc(a.x)
3

I expected to be referenced by aand a __init__. Then I decided to check.

So, I created a temporary variable bin the namespace __main__to have access to the variable x. He incremented the ref number by 1so it becomes 3(as expected):

>>> b = a.x
>>> grc(a.x)
4

, 1:

>>> del a
>>> grc(b)
3

, 2: one by b, - a ( ).

a __main__, , 1.

>>> del a
>>> grc(b)
3

. a , 100000, , b __main__.

, : 100000, b?


BrenBarn object() , - .

>>> class A():
    def __init__(self):
        self.x = object()


>>> a = A()
>>> b = a.x
>>> grc(a.x)
3
>>> del a
>>> grc(b)
2

a b, .

, , - , 100000.

+5
2

a.x - 10000. , __init__() A. :

>>> def f(): return 10000
>>> f.__code__.co_consts
(None, 10000)

del A

A A. Python 3.x( 2.x) , , , . ,

import gc
gc.collect()

del A b.

+2

, . Python , . self.x = object() ( x), grc(b)==2 .

+2

All Articles