destructors in python

Laurent POINTAL pointal at lure.u-psud.fr
Wed Sep 15 05:37:15 EDT 1999


On 14 Sep 1999 21:12:01 -0500, Kelly Burkhart <kburk at sky.net> wrote:

>: 
>: My tests show that the python destructor __del__ does not quite work
>: the way I expect.  The following program illustrates:
>: 
>: class Foo:
>: 
>:     def __init__(self):
>: 	print "Foo::__init__"
>: 
>:     def __del__(self):
>: 	print "Foo::__del__"
>: 
>: 
>: for i in range(2):
>:     print "----------"
>:     f = Foo()
>: 
>: The output:
>: 
>: [kburk at speedy python]$ ./tstdestruct.py
>: ----------
>: Foo::__init__
>: ----------
>: Foo::__init__
>: Foo::__del__
>: Foo::__del__
>: 
>: I expected to see the first __del__ before the second __init__.
[...deleted...]

f is not local to the loop!!!
If you wants it to works as you expected, do a f=None at the end of
the loop. Else, here is the scenario:

* The first Foo object is created (__init__ is called).
* The first Foo object is affected to f.
* The second Foo object is created (__init__ is called).
* The second Foo object is affected to f, so the first Foo object is
no more referenced (__del__ is called).
* f disapear (why? a local variable? a new affectation?), so the
second foo object is no more referenced (__del__ is called).

Hope this help.

A+

Laurent.

---
Laurent POINTAL - CNRS/LURE - Service Informatique Experiences
Tel/fax: 01 64 46 82 80 / 01 64 46 41 48
email  : pointal at lure.u-psud.fr  ou  lpointal at planete.net 




More information about the Python-list mailing list