Python: different behavior using gc module in interactive mode

后端 未结 2 1156
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 06:51

I wanted to be able to get a tuple of references to any existing object instances of a class. What I came up with was:

import gc

def instances(theClass):
           


        
2条回答
  •  隐瞒了意图╮
    2020-12-21 07:30

    When you work in interactive mode, there's a magic built-in variable _ that holds the result of the last expression statement you ran:

    >>> 3 + 4
    7
    >>> _
    7
    

    When you delete the c variable, del c isn't an expression, so _ is unchanged:

    >>> c = MyClass()
    >>> instances(MyClass)
    (<__main__.MyClass object at 0x00000000022E1748>,)
    >>> del c
    >>> _
    (<__main__.MyClass object at 0x00000000022E1748>,)
    

    _ is keeping a reference to the MyClass instance. When you call gc.collect(), that's an expression, so the return value of gc.collect() replaces the old value of _, and c finally gets collected. It doesn't have anything to do with the garbage collector; any expression would do:

    >>> 4
    4
    >>> instances(MyClass)
    ()
    

提交回复
热议问题