Problem deriving a class from the built-in file object

Pierre Rouleau Pierre_Rouleau at impathnetworks.com
Fri Apr 22 10:07:04 EDT 2005


Hi all!

I'm trying to extend the functionality of the file object by creating a 
class that derives from file.  MyFile class re-implements __init__(), 
write(), writelines() and close() to augment the capabilities of file.

All works fine, except for one thing:  'print >> myfile'  does not 
execute Myfile.write(), it executes the file.write().   If I execute 
myfile.write() explicitly, then Myfile.write() is called as expected.

I was not expecting that behaviour.  I though that 'print >> afileobject 
' would execute the afileobject.write() as you can easily obtain by 
defining a simple file-like class that implements write() and writeline().

I am running Python 2.3.4.  Can't move to 2.4 yet.

Is it the expected behavior?



# M y F i l e         -- Testing inheritance from file --
# ^^^^^^^^^^^
#
class MyFile(file):
     """ Testing new-style class inheritance from file"""

     #
     def __init__(self, name, mode="r", buffering=-1, verbose=False):
         """Constructor"""

         self.was_modified = False
         self.verbose = verbose
         super(MyFile, self).__init__(name, mode, buffering)
         if self.verbose:
             print "MyFile %s is opened.  The mode is: %s" % (self.name, 
self.mode)

     #
     def write(self, a_string):
         """ Write a string to the file."""

         super(MyFile, self).write(a_string)
         self.was_modified = True

     #
     def writelines(self, sequence):
         """ Write a sequence of strings to the file. """

         super(MyFile, self).writelines(sequence)
         self.was_modified = True

     #
     def close(self) :
         """Close the file."""

         if self.verbose:
             print "Closing file %s" % self.name

         super(MyFile, self).close()
         self.was_modified = False







More information about the Python-list mailing list