Problem deriving a class from the built-in file object
Peter Otten
__peter__ at web.de
Fri Apr 22 11:30:21 EDT 2005
Pierre Rouleau wrote:
> 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.
As a workaround, you can use delegation instead of inheritance:
>>> class File(object):
... def __init__(self, *args):
... self.file = file(*args)
... def __getattr__(self, name):
... return getattr(self.file, name)
... def write(self, s):
... print "writing", s
... self.file.write(s)
...
>>> f = File("tmp.txt", "w")
>>> for s in ["alpha", "beta", "gamma"]:
... print >> f, s
...
writing alpha
writing
writing beta
writing
writing gamma
writing
>>> f.close()
>>> File("tmp.txt").read()
'alpha\nbeta\ngamma\n'
> 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.
Nothing has changed with 2.4 in that respect.
> Is it the expected behavior?
I certainly didn't expect it either when I saw it for the first time.
Peter
More information about the Python-list
mailing list