在 python 中,假设执行以下操作:
# var is a variable, ClassName is the name of a class
var = ClassName(<params...>) # instatiate class to var
var = ClassName(<params...>) # reset variable to new instance
# or in loop
while 1:
var = ClassName(<params...>)
# use var ...
我的问题是,前一个实例何时被垃圾回收? 它发生在创建下一个实例之前还是之后?
最佳答案
请记住(定期)垃圾收集和reference-counting是两种不同的机制。在您的情况下,引用计数是相关的。
引用计数变为零的对象会立即释放(无需等待定期GC运行)。
[正如 @delnan 指出的那样,引用计数不是官方的 Python“功能”,而是 CPython 的具体实现细节。尽管如此,还是值得了解]
在您的情况下,您会得到两个并发的现有对象。这是事情发生的顺序:
a new object is created, and is referenced by name "var"
[you now have one existing object]
while True:
a new object is created
[you now have two existing objects]
it is referenced by name "var" (refcount += 1)
old object is no longer referenced by name "var" (refcount -= 1)
old object's refcount is now 0, it gets deallocated
[you now have one existing object]
如果您只希望存在一个并发对象,可以添加 del var
作为循环中的第一行。
关于Python垃圾回收发生在变量重置中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024359/