什么时候python删除变量? [英] when does python delete variables?

查看:195
本文介绍了什么时候python删除变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道python有一个自动垃圾回收器,所以它应该在没有更多引用时自动删除变量。



我的印象是,这不会发生局部变量(在函数内)。

  def funz(z):
x = f(z)#x是一个np.array并包含大量数据
x0 = x [0]
y = f (z + 1)#y是一个np.array并包含大量数据
y0 = y [0]

#是x在这里仍然可用?
return y [0],x [0]

是正确的方式保存内存?

  def funz(z):
x = f(z)#x是一个np.array和包含大量数据
x0 = x [0]
del x
y = f(z + 1)#y是一个np.array并包含大量数据
y0 = y [0]

return y [0],x [0]



<编辑:我编辑了我的例子,使它更接近我真正的问题。
在我真正的问题x和y不是列表,但类包含不同的长np.array编辑:我能够运行代码:
p>

  x = f(z)
x [0]
print(x0)

y = f(z + 1)
y0 = [0]
print(y0)


解决方案

实现使用引用计数来确定何时应该删除变量。



在变量超出范围之后(如您的示例中所示),如果没有剩余的引用,则内存将被释放。

  def a():
x = 5#x在函数执行期间的范围内
print x

a()
#x现在超出范围,没有引用,现在可以删除

除了列表中的字典键和元素之外,手动删除Python中的变量通常很少有理由。



虽然如<一个href =https://stackoverflow.com/questions/6146963/when-is-del-useful-in-python>这个问题,使用del可以用来显示意图。


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 still available here ?
    return y[0], x[0] 

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]  

        return y[0], x[0] 

EDIT: I have edited my example such that it is more similar to my real problem. In my real problem x and y are not list but class that contains different long np.array

EDIT: I am able to run the code:

x = f(z)
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

Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.

Though, as said in the answers to this question, using del can be useful to show intent.

这篇关于什么时候python删除变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆