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什么时候删除变量?
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
