Class destruction

Robert Dailey rcdailey at gmail.com
Wed Aug 22 14:17:44 EDT 2007


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.

Below is the source code to the class I'm attempting to add a destructor to:


import struct

#########################################################

class fout:
    def __init__( self, filename ):
        self._file = open( filename, "wb" )

    def write32( self, data ):
        # write out a 32-bit integer value
        self._file.write( struct.pack( "I", data ) )

    def write16( self, data ):
        # write out a 16-bit integer value
        self._file.write( struct.pack( "H", data ) )

    def write8( self, data ):
        # write out an 8-bit integer value
        self._file.write( struct.pack( "B", data ) )

    def write( self, data ):
        # write out a string literal
        self.write32( len( data ) )
        self._file.write( data )
        self._file.flush()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070822/8f4fb741/attachment.html>


More information about the Python-list mailing list