Bind an instance of a base to a subclass - can this be done?
Lou Pecora
pecoraREMOVE at THISanvil.nrl.navy.mil
Thu May 25 11:00:33 EDT 2006
I came up with this solution for subclassing the file object and making
some easy I/O functions (much thanks to Maric Michaud for pointing me in
the right direction). My goal was to make I/O of variables easy and in
a form that I could easily visually examine the file (which I often need
to do). The code also keeps it very clear as to what is being read in
or out in a single function call.
The class (inherited from file) in file ezfile.py:
# ==== File subclass from file for EZ I/O =======================
class ezfile(file):
# ---- Write items to file ------------------
# converts items list to string first using repr fcn.
def printline(_, ls):
sls=repr(ls)
_.writelines(sls)
# ---- Scan line from file & return items --------------------
# converts scanned string to list first using eval fcn.
def scanline(_,):
sls=_.readline()
return eval(sls)
An example in a Python session:
>>> from ezfile import *
# Define some variables
>>> x=2.334
>>> i= 7
>>> str='Some stuff here'
# Open a file and output the variables to it
>>> ff=ezfile('junk','w')
>>> ff.printline([x,i,str])
>>> ff.close()
# Open the same file and read the values back in to other variables
>>> f2=ezfile('junk','r')
>>> y,j,thestr=f2.scanline()
>>> print y,j,thestr
2.334 7 Some stuff here
>>> f2.close()
>>>
The file content looks like this:
[2.3340000000000001, 7, 'Some stuff here']
easy to see what is saved to the file.
It works! Thanks, again. Comments welcome.
-- Lou Pecora (my views are my own) REMOVE THIS to email me.
More information about the Python-list
mailing list