473,473 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problem deriving a class from the built-in file object

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


Jul 19 '05 #1
2 1335
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

Jul 19 '05 #2
Peter Otten wrote:
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:


Good idea, thanks!
Is it the expected behavior?

I certainly didn't expect it either when I saw it for the first time.

Peter


Is it something that will (or should) be changed in future version of
Python? I can't see any reason to keep the current behaviour.

Pierre
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Eric | last post by:
I've got a fairly simple setup that I thought would work, but I am getting link errors. template <class T> class TType { public: TType( void ) {} virtual ~TType( void ) {}
1
by: Mubashir Khan | last post by:
I am deriving a class from TextBox to implement a NumericBox. I am overriding OnGotFocus and OnLostFocus methods but On GotFocus is causing problems. Actually the commented lines are causing...
3
by: craigkenisston | last post by:
Hi, I have a class with 3 constructors, one takes no arguments, other take an string and other an xml document. I want to derive another class of it, I don't need a different constructor so I...
2
by: Eric Wenger | last post by:
I'm pretty new to C# and I'm trying to do what I believe should be a simple thing. I want to modify a program that is using the System.Net.NetworkInformation.Ping class to have some custom...
8
by: Russ | last post by:
Does it ever make sense to derive a class from a basic type such as float or int? Suppose, for example, that I want to create a class for physical scalars with units. I thought about deriving from...
15
by: Nindi73 | last post by:
HI If I define the class DoubleMap such that struct DoubleMap : public std::map<std::string, double>{}; Is there any overhead in calling std::map member functions ? Moreover are STL...
10
by: Mosfet | last post by:
Hi, I would like more info about deriving from an existing C struct. Let's say I am fed up with always writing the same code shown below : MYSTRUCT foo; memset( &foo, 0, sizeof(MYSTRUCT)...
12
by: Shraddha | last post by:
Can I stop people by deriving my class? I mean I don't want my class to be as a base class... Can I do that?
3
by: Valerie Hough | last post by:
I would like to derive my own class from the Socket class so that I can pass data from my client socket to the socket Server's OnAccept event.. I tried the syntax : public class MySocketClass:...
1
by: Christopher Pisz | last post by:
I set out to make a custom logger. Examining some other code laying around, I came across one that derived from ostream, and had a associated class derived from streambuf. Is this practice a good...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.