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

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

问题描述

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

<预><代码>>>>A类():定义杀死(自我):自我>>>a = A()>>>a.kill()>>>一个<__main__.A 实例在 0x01F23170>

解决方案

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

要亲眼看看,看看这两个函数执行时会发生什么:

<预><代码>>>>A类():... def kill_a(self):...打印自己... 自我... def kill_b(self):... 自我...打印自己...>>>a = A()>>>b = A()>>>a.kill_a()<__main__.A 实例在 0xb771250c>>>>b.kill_b()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 7 行,在 kill_b 中UnboundLocalError:赋值前引用了局部变量self"

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' 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天全站免登陆