-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Robert Dailey schrieb:
> Hi,
> 
> I'm wondering where the most appropriate location is to cleanup class
> objects. For example, i have a file handle as an instance attribute in one
> of my classes and I need to call f.close() on it when the class object falls
> out of scope. Any ideas? I've tried __del__() but I don't remember this
> working for some reason. I might try it again later just to be positive.

__del__(self) is the perfectly right place for such cleanup ... it gets
called once your instance is either deleted explicitly by you or it's
handled by the garbage collector when there are no more references.

The possible problem why this did not work four you is, that the
destruction by the garbage collector cannot be predicted ... it may well
take some time. If you try to open the same file from another class
before yours gets cleaned you run into trouble.

If you want to "reuse" the file, you will have to delete your classes
instance explicitly using the del statement ... this will also call the
destructor.

The below code works fine:

    def __del__( self ):
        self._file.close()
        print "File closed"

Hope that helps ... Nils
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGzISBzvGJy8WEGTcRAiOwAJ94fJza4/GVQsFmbXwsP8kdvQjV5wCfQktw
F/zPJAw0ayjYe5MGxPR1YqI=
=4Hl6
-----END PGP SIGNATURE-----
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to