是否可以删除(而不仅仅是取消链接)一个类?

时间:2015-05-06 23:57:18

标签: python class

假设我定义了一个类。

>>> class A(object):
>>>     pass

然后我要删除该类。我可以使用del取消与变量A的链接。

>>> del A
>>> A
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined

但是del实际上并没有删除类本身。我可以告诉它,因为它仍然列在object的子类中。

>>> object.__subclasses__()
[..., <class '__main__.A'>]

我认为这不会起作用,但是......

>>> del object.__subclasses__()[-1]
>>> object.__subclasses__()
[..., <class '__main__.A'>]

有没有办法真正删除该类,使其不再位于object.__subclasses__()

2 个答案:

答案 0 :(得分:2)

A之后,对del A的弱引用将会存在。这是必要的一个原因是允许循环引用而不阻止垃圾收集。试试这个以查看仍然引用它的内容(这是python解释器特有的,如果你作为脚本文件运行可能会有所不同):

>>> class A(object):
...     pass
...
>>> A
<class '__main__.A'>
>>> del A
>>> A
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined

>>> object.__subclasses__()[-2]
<class '__main__.A'>

>>> # using weakref
>>> import weakref
>>> weakref.getweakrefs(object.__subclasses__()[-2])
[<weakref at 0x800fa4ba8; to 'type' at 0x800f9d420 (A)>]

>>> # Another method using gc to see the referrers:
>>> import gc
>>> gc.collect()
>>> gc.get_referrers(object.__subclasses__()[-2])
[<__main__.A object at 0x800face90>, (<class '__main__.A'>, <type 'object'>), <attribute '__dict__' of 'A' objects>, <attribute '__weakref__' of 'A' objects>]

>>> # See the referents
>>> print '\n'.join(map(str, gc.get_referents(object.__subclasses__()[-2])))
{'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
(<class '__main__.A'>, <type 'object'>)
(<type 'object'>,)
<type 'object'>

关于这个问题的更多阅读:

http://pymotw.com/2/weakref/
https://docs.python.org/2/library/gc.html
https://docs.python.org/2.7/library/weakref.html
https://www.python.org/dev/peps/pep-0205/
https://docs.python.org/release/2.6.4/library/stdtypes.html#class.subclasses

答案 1 :(得分:0)

删除后您可以使用gc.collect

del A
from gc import collect
collect()
print( object.__subclasses__())