class destructor

bjorn bjorn at roguewave.com
Mon Jan 10 11:12:30 EST 2000


Oleg Broytmann wrote:

> On Mon, 10 Jan 2000, [iso-8859-2] Przemys³aw G. [iso-8859-2] Gawroñski wrote:
> > Is there 'automatic' destructor in python, like AClass::~AClass() in C++
> > ?
>
>    Method __del__(self) will be called when python is about to destroy the
> object (ie, reference count dropped to zero).

Although it doesn't get called for a number of useful cases, e.g. when part of a
circular datastructure, or when an exception is thrown (because the traceback
object has a reference?).  The only safe way I've found to implement
destructor-like behavior is:

class Foo:
    def __init__(self):
        ...
        self.open = 1

    def close(self):
        if self.open:
            # whatever is neccessary to 'delete' the object.

    def __del__(self):
        self.close()

then in the code where you want destructor-like behavior:

    foo = None
    try:
        foo = Foo() # exception can be called during init
        ...
    finally:
        if foo is not None:
            foo.close()

-- bjorn






More information about the Python-list mailing list