[TOC]
使用类
import os
os.chdir('C:\\Users\\alibaba\\Desktop\\Headfirstpython\\handledata2')
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins,secs) = time_string.split(splitter)
return(mins + '.' + secs)
class Athlete:
def __init__(self,a_name,a_dob=None,a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
def top3(self):
#显示最短的三个时间
return(sorted(set([sanitize(t) for t in self.times]))[0:3])
def add_time(self,time_value):
#增加一个计时值
self.times.append(time_value)
def add_times(self,list_of_times):
#增加一个或多个计时值
self.times.extend(list_of_times)
def get_coach_data(filename,separator = ','):
try:
with open(filename,"r") as file:
data = file.readline()
temp = data.strip().split(separator)
return (Athlete(temp.pop(0),temp.pop(0),temp))
except IOError as err:
print('File Error:' + str(ioerr))
return(None)
james = get_coach_data('james2.txt')
print(james.name+"'s fastest times are:"+str(james.top3()))
运行结果:
James Lee's fastest times are:['2.01', '2.16', '2.22']
使用子类
import os
os.chdir('C:\\Users\\alibaba\\Desktop\\Headfirstpython\\handledata2')
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins,secs) = time_string.split(splitter)
return(mins + '.' + secs)
class AthleteList(list):
def __init__(self,a_name,a_dob=None,a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
#self.times = a_times
self.extend(a_times)
def top3(self):
#显示最短的三个时间
return(sorted(set([sanitize(t) for t in self]))[0:3])
def get_coach_data(filename,separator = ','):
try:
with open(filename,"r") as file:
data = file.readline()
temp = data.strip().split(separator)
return (AthleteList(temp.pop(0),temp.pop(0),temp))
except IOError as err:
print('File Error:' + str(ioerr))
return(None)
james = get_coach_data('james2.txt')
print(james.name+"'s fastest times are:"+str(james.top3()))
运行结果:
James Lee's fastest times are:['2.01', '2.16', '2.22']
>>> james
['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22', '2-01', '2.01', '2:16']
>>> james.name
'James Lee'
>>> james.dob
'2002-3-14'
>>> james.extend(["1","1.2"])
>>> james
['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22', '2-01', '2.01', '2:16', '1', '1.2']
>>>
网友评论