__subclasses__的行为时类删除(Behaviour of __subclasses__

2019-07-18 10:54发布

编辑:广义由于NPE的评论的问题。

在Python 2.7.3交互式会话:

>>> class Foo(object):
...     pass
... 
>>> type("Bar", (Foo,), {})
<class '__main__.Bar'>
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>> 

也:

>>> class Foo(object):
...     pass
... 
>>> class Bar(Foo):
...     pass
... 
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>> del Bar
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]

为什么Bar仍然可以通过__subclasses__功能? 我本来期望它是垃圾回收。

相反,如果我希望它被垃圾收集,我该怎么办呢?

Answer 1:

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.



文章来源: Behaviour of __subclasses__ when classes are deleted