How do I define a __del__ method for an object?

Peter Otten __peter__ at web.de
Sun Mar 7 18:06:38 EST 2004


Stewart Midwinter wrote:

> I was looking through Swaroop's tutorial, "A Byte of Python", on Python
> objects,(http://www.python.g2swaroop.net/), and he mentions that you can
> define a __del__ function to completely delete object instances.
> However, when I try to define one in the attached script, not just one,
> but all, of the defined objects disappear.

?

> Can someone show me how to define a __del__ object that works on only
> one object instance?

A minimal example:

>>> class Person:
...     def __init__(self, name):
...             self.name = name
...             Person.population += 1
...     population = 0
...     def __del__(self):
...             Person.population -= 1
...
>>> stuart = Person("Stuart")
>>> Person.population
1
>>> del stuart
>>> Person.population
0
>>> stuart = Person("Stuart")
>>> midwinter = stuart
>>> print Person.population
1
>>> del midwinter
>>> Person.population
1
>>> del stuart
>>> Person.population
0

The __del__() method is called after the last binding to the object is
removed, i. e. the object becomes unreachable.

Explicitly deleting bindings is not very common. __del__() calls rather
occur when the last reference to an object goes out of scope:

>>> def transient():
...     p = Person("Peter")
...     print Person.population
...
>>> transient()
1
>>> Person.population
0
>>> mary = Person("Mary")
>>> Person.population
1
>>> mary = None
>>> Person.population
0

The caveat is that __del__() may not always be called immediately and
sometimes never.

Another point: Most objects do *not* need __del__() methods at all - I think
the ratio in the Python library is about 4 to 100, so don't spend too much
time on them.

Peter

PS: sayDie() is a badly chosen name as it pretends to inform the user while
the population is actualy changed.



More information about the Python-list mailing list