使用字典
#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‘]}
类和对象
#类定义方法
class classname:
def __init__(self):
#initialize code
...
- python要求每一个方法的第一个参数为调用对象实例(self)
简单测试代码:
>>> 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‘]
自定义类
#print_detail.py
from Athlete import Athlete
def 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))
return None
#Athlete.py
class 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‘]
若上面两个文件不再同一目录下,需要在print_detail.py中使用sys.path.append()加入Athlete.py所在路径
时间: 2024-10-22 06:48:24