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.