Python对象删除自身 [英] Python object deleting itself

查看:798
本文介绍了Python对象删除自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这行不通?我正在尝试删除一个类的实例.

Why won't this work? I'm trying to make an instance of a class delete itself.

>>> class A():
    def kill(self):
        del self


>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>

推荐答案

'self'只是对该对象的引用. "del self"将从kill函数的本地名称空间中删除"self"引用,而不是实际对象.

'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object.

要亲自了解这一点,请查看执行以下两个函数时会发生什么:

To see this for yourself, look at what happens when these two functions are executed:

>>> class A():
...     def kill_a(self):
...         print self
...         del self
...     def kill_b(self):
...         del self
...         print self
... 
>>> a = A()
>>> b = A()
>>> a.kill_a()
<__main__.A instance at 0xb771250c>
>>> b.kill_b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in kill_b
UnboundLocalError: local variable 'self' referenced before assignment

这篇关于Python对象删除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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