Second python program: classes, sorting
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon Aug 11 10:16:34 EDT 2008
WP a écrit :
> Hello, here are some new things I've problems with. I've made a program
> that opens and reads a text file. Each line in the file contains a name
> and a score. I'm assuming the file has the correct format. Each
> name-score pair is used to instantiate a class Score I've written. This
> works fine, but here's my problem: After reading the file I have list of
> Score objects. Now I want to sort them in descending order. But no
> matter how I write my __cmp__ the order remains unchanged.
You fixed this, so I'll just comment on the rest of the code...
(snip)
> Complete program:
> class Score:
Unless you have a compelling reason (mostly: compat with ages old Python
versions), better to use new-style classes:
class Score(object):
> def __init__(self, name_, score_):
> self.name = name_
> self.score = score_
cf Eric Brunel's comments here about the trailing underscores.
> def __str__(self):
> return "Name = %s, score = %d" % (self.name, self.score)
>
(snip)
> name = ""
> score = 0
Do you have any reason to have these as class attributes too ?
> # End class Score
>
> filename = "../foo.txt";
>
> try:
> infile = open(filename, "r")
> except IOError, (errno, strerror):
> print "IOError caught when attempting to open file %s. errno = %d,
> strerror = %s" % (filename, errno, strerror)
> exit(1)
cf Eric Brunel's comment wrt/ why this try/except clause is worse than
useless here.
> lines = infile.readlines()
File objects are their own iterators. You don't need to read the whole
file in memory.
> infile.close()
> lines = [l.strip() for l in lines] # Strip away trailing newlines.
>
> scores = []
>
> for a_line in lines:
> splitstuff = a_line.split()
>
> scores.append(Score(splitstuff[0], int(splitstuff[1])))
scores = []
mk_score = lambda name, score : Score(name, int(score))
infile = open(filename)
for line in infile:
line = line.strip()
if not line:
continue
scores.append(mk_score(*line.split()))
infile.close()
As a side note : I understand that this is a learning exercice, but in
real life, if that's all there is to your Score class, it's not really
useful - I'd personnally use a much simpler representation, like a list
of score / name pairs (which is easy to sort, reverse, update, turn into
a name=>scores or scores=>names dict, etc).
My 2 cents.
More information about the Python-list
mailing list