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 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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 ) {}
|
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...
|
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...
|
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...
|
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...
| |
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...
|
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)...
|
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?
|
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:...
|
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...
|
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,...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |