Using dictionaries
#print_detail同之前的print_times>>> import print_detail >>> james2 = print_detail.print_detail(‘james2‘)>>> james2[‘James Lee‘, ‘2002:3:14‘, ‘2:34‘, ‘3:21‘, ‘2:34‘, ‘2:45‘, ‘3:01‘, ‘2:01‘, ‘2:01‘, ‘3:10‘, ‘2:22‘, ‘2:01‘, ‘2:01‘, ‘2:16‘]>>> james2Dic = {}>>> james2Dic[‘name‘] = james2.pop()>>> james2Dic[‘dob‘] = james2.pop()>>> james2Dic[‘times‘] = james2>>> james2Dic{‘dob‘: ‘2:01‘, ‘name‘: ‘2:16‘, ‘times‘: [‘James Lee‘, ‘2002:3:14‘, ‘2:34‘, ‘3:21‘, ‘2:34‘, ‘2:45‘, ‘3:01‘, ‘2:01‘, ‘2:01‘, ‘3:10‘, ‘2:22‘, ‘2:01‘]}
Classes and objects
#类定义方法class classname: def __init__(self): #initialize code ...
- Python requires that the first argument of each method be the calling object instance (self)
Simple test Code:
>>> class Athlete:... def __init__(self,name,dob=None,times=[]):... self.name = name... self.dob = dob... self.times = times... >>> type(Athlete)<type ‘classobj‘>>>> sarah = Athlete(‘sarah Sweeney‘,‘2002-02-22‘,[‘2:45‘, ‘3:01‘, ‘2:01‘])>>> james = Athlete(‘james Jones‘)>>> type(james)<type ‘instance‘>>>> james<__main__.Athlete instance at 0x10691a5a8>
>>> james.name‘james Jones‘>>> james.dob>>> james.times[]>>> sarah.name‘sarah Sweeney‘>>> sarah.dob‘2002-02-22‘>>> sarah.times[‘2:45‘, ‘3:01‘, ‘2:01‘]
Custom Classes
#print_detail.pyfrom Athlete import Athletedef print_detail(file_name): try: with open(file_name+‘.txt‘) as data: time_list = data.read().replace(‘-‘,‘:‘).replace(‘.‘,‘:‘) time_list = time_list.strip().split(‘,‘) return Athlete(time_list.pop(0),time_list.pop(0),time_list) except IOError as err: print(‘file error:‘+str(err))
#Athlete.pyclass Athlete: def __init__(self,name,dob=None,times=[]): self.name = name self.dob = dob self.times = times def top3(self): return sorted(set(self.times))[0:3] def add_time(self,a_time): self.times.append(a_time) def add_times(self,time_list): self.times.extend(time_list)
>>> import print_detail>>> james = print_detail.print_detail(‘james2‘)>>> type(james)<type ‘instance‘>>>> james.name‘James Lee‘>>> james.dob‘2002:3:14‘>>> james.top3()[‘2:01‘, ‘2:16‘, ‘2:22‘]>>> james.add_time(‘1.99‘)>>> james.top3()[‘1.99‘, ‘2:01‘, ‘2:16‘]>>> james.add_times([1.11,1.22])>>> james.top3()[1.11, 1.22, ‘1.99‘]
If the above two files are no longer in the same directory, you need to use Sys.path.append () in print_detail.py to join the athlete.py path
Head_first_python Study Notes (iv)