[Tutor] class data

dman dsh8290@rit.edu
Mon, 3 Dec 2001 12:39:38 -0500


On Mon, Dec 03, 2001 at 11:44:53AM -0500, Tom Jenkins wrote:
| On Mon, 2001-12-03 at 11:14, alan.gauld@bt.com wrote:
...
| > > > class Entry:
| > > >    def __init__(s, nm,ph,em):
| > > >       s.name = nm
| > > >       s.phone = ph
| > > >       s.email = em
| > > >    def saveme(s,flnm):
| > > >       f = open(flnm,'a')
| > > >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
| > 
| > Oops, try 
| >           f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)
| > 
| 
| I like using variable substitution; so my version would be:
| f.write('%s\t%s\t%s' % (s.name, s.phone, s.email))
| 
| or
| 
| f.write('%(nm)s\t%(ph)s\t%(em)s' % ({'nm':s.name, 'ph':s.phone,
| 'em':s.email}))
| 
| i prefer this as its hard to see that Alan is using backticks ( ` ) for
| s.name, s.phone

I pick whichever style is clearest for the data I have at that time.
In this case the data should already be a string, so

f.write( s.name + "\t" + s.phone + "\t" + s.email )

would work, and has the least amount of noise (in this case).

There is also the alternative of using the str() function/factory
instead of backticks.  (Oh, but I don't remember if backticks call
str() or repr(), but you can use repr() if you want to be explicit)

I like string interpolation especially if I want some (stati) text
around the data, or if I want to format numbers.  The named
interpolation tends to just add noise for simple lines (like above),
but is great if the same data is to be output multiple times, or if it
comes as a dictionary already.

-D

-- 
 
How great is the love the Father has lavished on us,
that we should be called children of God!
        1 John 3:1