python怎么删除对象,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

解决方案

'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()

>>> b.kill_b()

Traceback (most recent call last):

File "", line 1, in

File "", line 7, in kill_b

UnboundLocalError: local variable 'self' referenced before assignment

你可能感兴趣的:(python怎么删除对象)