Python object deleting itself

后端 未结 14 2014
一向
一向 2020-11-27 04:23

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

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


>>>          


        
14条回答
  •  误落风尘
    2020-11-27 04:52

    '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 "", line 1, in 
      File "", line 7, in kill_b
    UnboundLocalError: local variable 'self' referenced before assignment
    

提交回复
热议问题