Python垃圾是否会在更高的范围内收集变量,而变量将永远不会再使用?
例如,在代码中:
a = [1, 2, 3, 4] # huge list
y = sum(a)
print( do_stuff(y) )
列表a
的内存是否会在程序结束之前被释放? do_stuff
功能调用是否必须使用a
不断占用内存的所有操作,即使a
永远不会再使用?
而且,如果a
没有收集垃圾,一旦我完成了它,是否是手动设置a = none
的解决方案?
For example, in the code:
a = [1, 2, 3, 4] # huge list
y = sum(a)
print( do_stuff(y) )
Will the memory for the list a
ever get freed up before the program ends? Will the do_stuff
function call have to do all its stuff with a
constantly taking up memory, even though a
's never going to be used again?
And if a
doesn't get garbage collected, is the solution to manually set a=None
once I'm done using it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想象
do_stuff
做到了这一点:并且用户输入
a
,以便毕竟在此使用列表。 Python不知道这不会发生,它必须阅读用户的思想。考虑这样的微不足道的情况:
现在很明显,
a
不再使用,所以Python 可以弄清楚吗?好吧...打印
不再是关键字/语句。 Python必须弄清楚您没有使用a
的东西覆盖print
。即使您没有,它也需要知道其自己的打印
不使用a
。您必须自己删除它。我将使用
del a
。 (除非您想要a
仍然存在并具有值none
)。Imagine
do_stuff
did this:And the user enters
a
, so that the list is used there after all. Python can't know that that won't happen, it would have to read the user's mind.Consider a trivial case like this:
Now it's clear that
a
doesn't get used anymore, so Python could figure that out right? Well...print
isn't a keyword/statement anymore. Python would have to figure out that you didn't overwriteprint
with something that does usea
. And even if you didn't, it would need to know that its ownprint
doesn't usea
.You'll have to delete it yourself. I'd use
del a
. (Unless you wanta
to still exist and have the valueNone
).a
除非超出范围(即。Python's垃圾收集器使用一个名为参考计数)的系统。简而言之,所有变量都有一个参考计数器,当创建对变量的引用时会增加,并且当变量设置为
none
时,则降低。例子:
a
will never be freed unless it goes out of scope (ie. it was in a function to begin with), or you manually set it toNone
.Python's garbage collector uses a system called reference counting. In short, all variables have a reference counter that is incremented when a reference to the variable is created, and decremented when an variable is set to
None
or when it goes out of scope.Example: