If a class is defined in interpreter environment:
class C(object):
def __init__(self, val):
self.x = val
Then instantiated without names:
>>> C(1)
>>> C(2)
>>>
Then we can use underscore _ to refer to C(2)
, so here is my question:
- Since the underscore '_' refer to
C(2)
, can we say the reference counter forC(2)
is still 1? So the python gc will not free the memory taken byC(2)
? - As far as I know, after these
C(2)
is executed, no names will refer toC(1)
, so can I say as soon asC(2)
is executed,C(1)
's memory will be freed by python gc?
These are actually 4 questions, one bold font to one.
gc: short for garbage collection
EDIT
Let me make my first question more clear by commenting directly into the codes.
>>> C(1) # Press Enter Key and run
>>>
>>> At Here, what is the exact reference count for the previous anonymous object "C(1)"?
>>> And how to prove?
>>>
>>> C(2) # Press Enter Key and run
>>>
>>> At Here, what is the exact reference count for the previous anonymous object "C(1)"?
>>> And how to prove?
C(1)
orC(2)
as last line of the interpreter behaves differently when they are in the middle or to the up of the code.If
C(1)
is at the last line, python interpreter will store it as<__main__.C object at 0x00000000********>
, so actually it will have a name attached to it. If you checknumber_of_instances(C)
, the result will be 1.If
C(1)
is not at the last line, this temporary anonymous object is just destroyed and disappeared.Check the following testing codes.
You can use
number_of_instances
to show if there is anyC
object resides in memory.1.anonymous object not at last line
2.anonymous object at last line
3.underscore
_
will rememberC(3)
if it is the last lineBut in this case, the reference counter never counts reference from
_
, it only counts<__main__.C object at 0x0000000006AA06D8>
which you didn't observe.A guess here:
_
is not ingc.garbage
list. If you runC(1)
,print(number_of_instances(C))
successively,number_of_instances
will not check into_
which may be storing the previousC(1)
See: sys.getrefcount continuation
@allen, thank you so much for your answer.
Based on your guess, I made the following code:
So the _ underscore is only used for storing the value of last expression in interpreter of "Single Step Mode", not for "Continuous Mode".
This might be a common mistake made by beginners.
Anyway, thank you so much for your answer!