when does python delete variables?(python什么时候删除变量?)
问题描述
我知道 python 有一个自动垃圾收集器,因此它应该在不再引用变量时自动删除变量.
I know that python has an automatic garbage collector and so it should automatically delete variables when there are no more reference to them.
我的印象是局部变量(函数内部)不会发生这种情况.
My impression is that this does not happen for local variables (inside a function).
def funz(z):
x = f(z) # x is a np.array and contains a lot of data
x0 = x[0]
y = f(z + 1) # y is a np.array and contains a lot of data
y0 = y[0]
# is x and y still available here?
return y0, x0
del x是节省内存的正确方法吗?
Is del x the right way to save memory?
def funz(z):
x = f(z) # x is a np.array and contains a lot of data
x0 = x[0]
del x
y = f(z + 1) # y is a np.array and contains a lot of data
y0 = y[0]
del y
return y0, x0
我已经编辑了我的示例,使其更类似于我的实际问题.在我的真正问题中,x 和 y 不是列表,而是包含不同大型 np.array 的类.
I have edited my example such that it is more similar to my real problem.
In my real problem x and y are not lists but classes that contain different large np.array.
我能够运行代码:
x = f(z)
x0 = x[0]
print(x0)
y = f(z + 1)
y0 = [0]
print(y0)
推荐答案
实现使用引用计数来确定何时应该删除变量.
Implementations use reference counting to determine when a variable should be deleted.
变量超出范围后(如您的示例),如果没有剩余的引用,则内存将被释放.
After the variable goes out of scope (as in your example) if there are no remaining references to it, then the memory will be freed.
def a():
x = 5 # x is within scope while the function is being executed
print x
a()
# x is now out of scope, has no references and can now be deleted
除了列表中的字典键和元素之外,通常很少有理由在 Python 中手动删除变量.
Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.
不过,正如对这个问题的回答中所说,使用 del可用于显示意图.
Though, as said in the answers to this question, using del can be useful to show intent.
这篇关于python什么时候删除变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python什么时候删除变量?
基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
