Python 从内存中删除类实例
在我的程序中,我创建了大量的类实例。数量取决于程序运行的时间。但是,在运行某个代码之后,我根本不需要实例。我怎样才能完全从记忆中删除它们 简单示例代码:Python 从内存中删除类实例,python,python-3.x,class,memory,instance,Python,Python 3.x,Class,Memory,Instance,在我的程序中,我创建了大量的类实例。数量取决于程序运行的时间。但是,在运行某个代码之后,我根本不需要实例。我怎样才能完全从记忆中删除它们 简单示例代码: class Player: def __init__(self, color): self.color = color for n in range(1000): p = Player('black') 在这种情况下,delp会完全删除该实例吗?在这种情况下,delp只会删除对Player对象的引用,以便垃圾
class Player:
def __init__(self, color):
self.color = color
for n in range(1000):
p = Player('black')
在这种情况下,
delp
会完全删除该实例吗?在这种情况下,delp
只会删除对Player
对象的引用,以便垃圾收集器稍后可以拾取该对象
然而,当它超出范围时也会发生这种情况
在大多数日常Python中,不需要使用显式的
del
语句。当不再引用它们时,Python会将它们从内存中删除。如果您有Player
实例引用了其他Player
实例(例如:p.队友=[玩家列表]
),那么您可能会得到循环引用,从而防止它们被垃圾收集。在这种情况下,你应该考虑这个模块。
例如:
>>>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'
sam=Player('blue')
>>>rob=玩家(“绿色”)
>>>sam.team=[weakref.ref(sam),weakref.ref(rob)]
>>>rob.team=[weakref.ref(sam),weakref.ref(rob)]
>>>#现在可以删除sam和rob,但我们对'p.team'的内容做了一些更改:
>>>#如果两者仍然存在:
>>>rob.team[0]()是sam#调用'ref'对象时,如果该对象仍然存在,则返回它所引用的对象
真的
>>>德尔萨姆
>>>rob.team[0]()#调用已删除的'ref'对象将返回'None'`
没有一个
>>>rob.team[0]().color#sam已不存在,因此我们无法获取他的颜色
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“非类型”对象没有属性“颜色”
在Python中无法删除实例。相反,您可以删除对实例的引用,一旦它们全部消失,对象将被回收。没有引用的对象将由垃圾收集器收集。如果我使用实例的属性作为参数来创建另一个实例,该怎么办?这会导致你所说的循环引用吗?i、 e.
b=Player(p.color)
@BasVeldenp.color
将引用您在创建p
时创建的字符串对象。如果多个Player
实例引用同一字符串,则在删除所有引用该字符串的Player
实例之前,不会删除该字符串。虽然这个概念是跨数据类型的(如果颜色是一个列表,那么内存中只存在一个列表,并且有多个引用),但字符串特别具有一个特殊的附加机制,可以帮助减少内存使用和复制。