Class destructor

Mongryong Mongryong at
Thu Feb 13 17:33:30 CET 2003

On Thu, 2003-02-13 at 09:46, Roberto Cavada wrote:
> class A:
>      def __init__(self):
>          self.ref = self
>          print "Built instance of A"
>          return
>      def __del__(self):
>          print "Destroying instance of A"
>          return
>      pass # end of class
> a1 = A()
> del a1  # This does not call A.__del__

If you keep in mind that Python uses 'reference counting' for garbage
collecting, you can see why the 'del a1' appears to be doing nothing. 
>From above, there are '2' references to the object created by 'a1=A()':
a1 and a1.ref both point to that object.  When 'del a1' is executed 'a1'
no longers points to anything (ie. a1=Null).  This reduces the
'reference count' to 1.  Hence, the object pointed to by 'a1' can not
yet be deleted.  So, you now have something similar to a C/C++'s 'lost

> a2 = A()
> del a2.ref # Neither does this
> del a2  # This calls it
As explained above 'a2=A()' creates two references.  'del a2.ref'
removes 1 reference. 'del a2' removes the other reference.  Hence, no
more references, so the destructor is called.

So, if you wanted 'circular' references like the above example, you'll
have to call delete the inner reference first.  

More information about the Python-list mailing list