Page 232 -
P. 232
class athlete
Here’s your code (except for the santize() function, which doesn’t
need to change). With your pencil, you were to write code to define the
Athlete class. In addition to the __init__() method, you were to
define a new method called top3() that, when invoked, returns the top
three times. You were to be sure to adjust the get_coach_data()
function to return an Athlete object as opposed to a dictionary, and
you weren’t to forget to amend print(), too.
class Athlete:
def __init__(self, a_name, a_dob=None, a_times=[]):
self.name = a_name There’s nothing new here as this
code is taken straight from the
self.dob = a_dob most recent IDLE session.
self.times = a_times
Did you remember to
use “self”?
def top3(self):
return(sorted(set([sanitize(t) for t in self.times]))[0:3])
def get_coach_data(filename): Remove the dictionary creation
try: code and replace it with Athlete
object creation code instead.
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
return({'Name' : templ.pop(0),
'DOB' : templ.pop(0), Athlete(templ.pop(0), templ.pop(0), templ)
'Times': str(sorted(set([sanitize(t) for t in templ]))[0:3])})
except IOError as ioerr:
print('File error: ' + str(ioerr))
return(None) Use the dot notation to get Invoke the “top3()”
at your data. method and convert its
results to a string prior
james = get_coach_data('james2.txt') to its display on screen.
james.name str(james.top3())
print(james['Name'] + "'s fastest times are: " + james['Times'])
196 Chapter 6