Class destructor
Jp Calderone
exarkun at intarweb.us
Thu Feb 13 14:42:16 EST 2003
On Thu, Feb 13, 2003 at 11:33:30AM -0500, Mongryong wrote:
> 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.
Actually, reference counting and garbage collection are two separate
methods. Straight reference counting is used for all non-cyclic structures.
The garbage collector only comes into play when an actual cycle is found.
It runs periodically and notices when a group of objects are only reachable
from themselves. If there is no __del__ method, it destroys them, otherwise
it marks them as uncollectable garbage.
> 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 is a bad way to look at it. a1 is no longer defined after you delete
it.
> 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 pointer'.
"Lost pointer" (Which I believe is a less commonly used term for "dangling
pointer", though I may be mistaken) in C is when a pointer refers to an area
of memory that has been freed. This isn't the case in Python, as it is
[almost] impossible to refer to freed memory locations.
This really is just a cycle.
>
> > 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.
>
Jp
--
up 5 days, 0:28, 3 users, load average: 0.06, 0.16, 0.08
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030213/46af4dae/attachment.sig>
More information about the Python-list
mailing list