Python object deleting itself Python object deleting itself python python

Python object deleting itself


'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_bUnboundLocalError: local variable 'self' referenced before assignment


You don't need to use del to delete instances in the first place. Once the last reference to an object is gone, the object will be garbage collected. Maybe you should tell us more about the full problem.


I think I've finally got it!
NOTE: You should not use this in normal code, but it is possible.This is only meant as a curiosity, see other answers for real-world solutions to this problem.


Take a look at this code:

# NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it.import weakrefclass InsaneClass(object):    _alive = []    def __new__(cls):        self = super().__new__(cls)        InsaneClass._alive.append(self)        return weakref.proxy(self)    def commit_suicide(self):        self._alive.remove(self)instance = InsaneClass()instance.commit_suicide()print(instance)# Raises Error: ReferenceError: weakly-referenced object no longer exists

When the object is created in the __new__ method, the instance is replaced by a weak reference proxy and the only strong reference is kept in the _alive class attribute.

What is a weak-reference?

Weak-reference is a reference which does not count as a reference when the garbage collector collects the object. Consider this example:

>>> class Test(): pass>>> a = Test()>>> b = Test()>>> c = a>>> d = weakref.proxy(b)>>> d<weakproxy at 0x10671ae58 to Test at 0x10670f4e0> # The weak reference points to the Test() object>>> del a>>> c<__main__.Test object at 0x10670f390> # c still exists>>> del b>>> d<weakproxy at 0x10671ab38 to NoneType at 0x1002050d0> # d is now only a weak-reference to None. The Test() instance was garbage-collected

So the only strong reference to the instance is stored in the _alive class attribute. And when the commit_suicide() method removes the reference the instance is garbage-collected.