Behaviour of __subclasses__ when classes are deleted

前端 未结 1 588
青春惊慌失措
青春惊慌失措 2021-01-06 12:06

Edit: Generalised the question due to NPE\'s comment.

In a Python 2.7.3 interactive session:

>>> class Foo(object):
...     pass
... 
>&g         


        
相关标签:
1条回答
  • 2021-01-06 12:56

    See this thread. It would seem that what happens is the class's __mro__ attribute stores a reference to itself, creating a reference cycle. You can force a full gc run which will detect the cycle and delete the object:

    >>> class Foo(object): pass
    >>> class Bar(Foo): pass
    >>> import gc
    >>> del Bar
    >>> gc.collect()
    3
    >>> Foo.__subclasses__()
    []
    

    Alternatively, if you enter other commands for a while, the gc will run on its own and collect the cycle.

    Note that you have to be a bit careful when testing this interactively, because the interactive interpreter stores a reference to the most recently returned value in the "last value" variable _. If you explicitly look at the subclass list and then immediately try to collect, it won't work, because the _ variable will hold a list with a strong reference to the class.

    0 讨论(0)
提交回复
热议问题