在我的程序中,我创建了无休止的类实例。该数量取决于程序运行多长时间。但是,在运行某些代码之后,我根本不需要这些实例。我如何才能将它们从内存中完全删除?
简单的示例代码:
class Player:
def __init__(self, color):
self.color = color
for n in range(1000):
p = Player('black')
在这种情况下,del p
是否会完全删除该实例?
答案 0 :(得分:2)
在这种情况下,del p
仅会删除对Player
对象的 reference ,以便以后可以由垃圾收集器将其拾取。
但是,当超出范围时也会发生这种情况。
在大多数日常Python中,无需使用显式的del
语句。
答案 1 :(得分:2)
Python中无法删除实例。取而代之的是,您可以删除对实例的引用,一旦引用全部消失,则将回收该对象。
答案 2 :(得分:1)
当不再引用它们时,Python会将它们从内存中删除。如果您有Player
个实例引用了其他Player
个实例(例如:p.teammates = [list of Players]
),则可能会以循环引用结尾,这可能会阻止它们被垃圾回收。在这种情况下,您应该考虑使用weakref
模块。
例如:
>>>sam = Player('blue')
>>>rob = Player('green')
>>>sam.team = [sam, rob]
>>>rob.team = [sam, rob]
>>> #sam and rob may not be deleted because they contain
>>> #references to eachother so the reference count cannot reach 0
>>>del sam #del is a way to manually dereference an object in an interactive prompt. Otherwise the interpreter cannot know you won't use it again unlike when the entire code is known at the beginning.
>>>print(rob.team[0].color) #this prints 'blue' proving that sam hasn't been deleted yet
blue
那我们该如何解决呢?
>>>sam = Player('blue')
>>>rob = Player('green')
>>>sam.team = [weakref.ref(sam), weakref.ref(rob)]
>>>rob.team = [weakref.ref(sam), weakref.ref(rob)]
>>> #now sam and rob can be deleted, but we've changed the contents of `p.team` a bit:
>>> #if they both still exist:
>>>rob.team[0]() is sam #calling a `ref` object returns the object it refers to if it still exists
True
>>>del sam
>>>rob.team[0]() #calling a `ref` object that has been deleted returns `None`
None
>>>rob.team[0]().color #sam no longer exists so we can't get his color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'color'