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
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01