__subclasses__在删除类时的行为 [英] Behaviour of __subclasses__ when classes are deleted
问题描述
在Python 2.7.3交互式会话中:
>>> class Foo(object):
... pass
...
>>> type(Bar,(Foo,),{})
< class'__main __。Bar'>
>>> Foo .__子类__()
[< class'__main __。Bar'>]
>>>
另外:
>>> class Foo(object):
... pass
...
>>>班级Bar(Foo):
...通过
...
>>> Foo .__子类__()
[< class'__main __。Bar'>]
>>> del Bar
>>> Foo .__子类__()
[< class'__main __。Bar'>]
Bar
如何通过 __子类__
函数仍然可用?如果我希望它被垃圾收集,我该怎么做?
请参阅此线程。看起来会发生什么是该类的 __ mro __
属性存储对自身的引用,从而创建一个引用循环。您可以强制执行完整的gc运行,它将检测周期并删除对象:
>>> class Foo(object):pass
>>> class Bar(Foo):pass
>>> import gc
>>> del Bar
>>> gc.collect()
3
>>> Foo .__子类__()
[]
或者,如果您输入其他命令一段时间,gc将自行运行并收集周期。
请注意,交互式测试时必须小心,因为交互式解释器存储对最后一个值变量 _
中最近返回的值。如果您明确地查看子类列表,然后立即尝试收集,它将不起作用,因为 _
变量将包含对该类的强引用的列表。
Edit: Generalised the question due to NPE's comment.
In a Python 2.7.3 interactive session:
>>> class Foo(object):
... pass
...
>>> type("Bar", (Foo,), {})
<class '__main__.Bar'>
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>>
Also:
>>> class Foo(object):
... pass
...
>>> class Bar(Foo):
... pass
...
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>> del Bar
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
How come Bar
is still available via the __subclasses__
function? I would have expected it to be garbage collected.
Conversely, if I want it to be garbage collected, how do I do it?
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.
这篇关于__subclasses__在删除类时的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!