【Python实战14】继承Python内置的list
"定义Atylete类" class Atylete: def __init__(self,a_name,a_birthday=None,a_time=[]): self.name=a_name self.birthday=a_birthday self.time=a_time def top3(self): return(sorted(set([sanitize(t) for t in self.time]))[0:3]) def add_time(self,time_value): self.time.append(time_value) def add_times(self,list_of_time): self.time.extend(list_of_time) """转换时间格式""" 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) """读取文件内容,并按逗号进行拆分""" def get_coach_data(filename): try: with open(filename) as file: data = file.readline() temp=data.strip().split(‘,‘) return(Atylete(temp.pop(0),temp.pop(0),temp)) except IOError as error: print(‘File Error:‘+str(error)) return(None) """读取文件的内容""" james = get_coach_data(‘james.txt‘) julie = get_coach_data(‘julie.txt‘) mikey = get_coach_data(‘mikey.txt‘) sarah = get_coach_data(‘sarah.txt‘) """打印姓名、生日和最快的三个时间""" print(james.name+"的生日是:"+james.birthday+",最快的三个时间是:"+str(james.top3())) print(julie.name+"的生日是:"+julie.birthday+",最快的三个时间是:"+str(julie.top3())) print(mikey.name+"的生日是:"+mikey.birthday+",最快的三个时间是:"+str(mikey.top3())) print(sarah.name+"的生日是:"+sarah.birthday+",最快的三个时间是:"+str(sarah.top3()))
在进行代码修改之前,我们首先了解下如何继承一个类,这里以继承list类为例:
>>> class NameList(list): def __init__(self,a_name): list.__init__([]) self.name=a_name这里定义了一个NameList类,继承自list类,接下来实例化一个NameList类的实例:
>>> john=NameList(‘john‘) >>> type(john) <class ‘__main__.NameList‘> >>> >>> dir(john) [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dict__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__module__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘name‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]通过dir函数我们可以看到john对象具有的所有的功能,可以看到这些功能都是继承自list类的
>>> john [] >>> john.name ‘john‘ >>> john.append(‘Bass player‘) >>> john [‘Bass player‘] >>> john.extend([‘Composer‘,‘Musician‘]) >>> john [‘Bass player‘, ‘Composer‘, ‘Musician‘]可以看到john可以随意的使用list的所有功能。
下面就让我们修改之前的代码吧,修改后的代码如下:
"定义Atylete类" class AtyleteList(list): def __init__(self,a_name,a_birthday=None,a_time=[]): list.__init__([]) self.name=a_name self.birthday=a_birthday self.extend(a_time) def top3(self): return(sorted(set([sanitize(t) for t in self]))[0:3]) def add_time(self,time_value): self.time.append(time_value) def add_times(self,list_of_time): self.time.extend(list_of_time) """转换时间格式""" 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) """读取文件内容,并按逗号进行拆分""" def get_coach_data(filename): try: with open(filename) as file: data = file.readline() temp=data.strip().split(‘,‘) return(AtyleteList(temp.pop(0),temp.pop(0),temp)) except IOError as error: print(‘File Error:‘+str(error)) return(None) """读取文件的内容""" james = get_coach_data(‘james.txt‘) julie = get_coach_data(‘julie.txt‘) mikey = get_coach_data(‘mikey.txt‘) sarah = get_coach_data(‘sarah.txt‘) """打印姓名、生日和最快的三个时间""" print(james.name+"的生日是:"+james.birthday+",最快的三个时间是:"+str(james.top3())) print(julie.name+"的生日是:"+julie.birthday+",最快的三个时间是:"+str(julie.top3())) print(mikey.name+"的生日是:"+mikey.birthday+",最快的三个时间是:"+str(mikey.top3())) print(sarah.name+"的生日是:"+sarah.birthday+",最快的三个时间是:"+str(sarah.top3()))运行结果如下:
>>> ================================ RESTART ================================ >>> James Lee的生日是:2002-3-14,最快的三个时间是:[‘2.01‘, ‘2.16‘, ‘2.22‘] Julie Jones的生日是:2002-8-17,最快的三个时间是:[‘2.11‘, ‘2.23‘, ‘2.59‘] Mikey McManus的生日是:2002-2-24,最快的三个时间是:[‘2.22‘, ‘2.31‘, ‘2.38‘] Sarah Sweeney的生日是:2002-6-17,最快的三个时间是:[‘2.18‘, ‘2.21‘, ‘2.22‘]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。