本文介绍了在局部变量上使用显式del在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中使用显式

使用 del

code>是确保
a对象的 __ del __ 方法被调用的唯一方法


这是非常重要的。为了帮助,让我们使用 __ del __ 创建一个类,并检查它是否被调用:

 >>>> class visdel(object):
... def __del __(self):print'del',id(self)
...
>>> d = visdel()
>>>> a = list()
>>>> a.append(d)
>>>> del d
>>>>

del 不会确保 __ del __ 被调用: del 删除一个引用,只有删除最后引用才会调用 __ del __ 。所以,也:

 >>> a.append(visdel())
>>> a [:] = [1,2,3]
del 550864
del 551184

当最后一个引用消失时(包括不涉及 del 的方式,例如这种情况下的切片分配或其他名称重新绑定,其他插槽),然后 __ del __ 被调用 - 是否 del



因此,除非你特别需要清理命名空间(通常是模块的名称空间)命名空间,但可以想象一个类或实例),因为某些特定的原因,不要打扰 del (它可以偶尔方便地从容器中删除项目,我发现我经常使用容器的 pop 方法或项目或切片分配,即使 ! - )。


What are the best practices and recommendations for using explicit del statement in python? I understand that it is used to remove attributes or dictionary/list elements and so on, but sometimes I see it used on local variables in code like this:

def action(x):
    result = None
    something = produce_something(x)
    if something:
        qux = foo(something)
        result = bar(qux, something)
        del qux
    del something
    return result

Are there any serious reasons for writing code like this?

Edit: consider qux and something to be something "simple" without a __del__ method.

解决方案

I don't remember when I last used del -- the need for it is rare indeed, and typically limited to such tasks as cleaning up a module's namespace after a needed import or the like.

In particular, it's not true, as another (now-deleted) answer claimed, that

and it's very important to understand this. To help, let's make a class with a __del__ and check when it is called:

>>> class visdel(object):
...   def __del__(self): print 'del', id(self)
... 
>>> d = visdel()
>>> a = list()
>>> a.append(d)
>>> del d
>>>

See? del doesn't "make sure" that __del__ gets called: del removes one reference, and only the removal of the last reference causes __del__ to be called. So, also:

>>> a.append(visdel())
>>> a[:]=[1, 2, 3]
del 550864
del 551184

when the last reference does go away (including in ways that don't involve del, such as a slice assignment as in this case, or other rebindings of names and other slots), then __del__ gets called -- whether del was ever involved in reducing the object's references, or not, makes absolutely no difference whatsoever.

So, unless you specifically need to clean up a namespace (typically a module's namespace, but conceivably that of a class or instance) for some specific reason, don't bother with del (it can be occasionally handy for removing an item from a container, but I've found that I'm often using the container's pop method or item or slice assignment even for that!-).

这篇关于在局部变量上使用显式del在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 14:36