使用class定义类:
每个定义的类都有一个特殊的方法,名为__init__(),可以通过这个方法控制如何初始化对象。
创建对象实例
注意:Python中没有定义构造函数“new”的概念,Python会为你完成对象创建。然后你可以使用__init__()定制对象的初始状态。
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([nester.sanitize(t) for t in self.times]))[0:3] def get_coach_data_new2(filename): try: with open(filename) as f: data = f.readline().strip().split(',') return Athlete(data.pop(0),data.pop(0),data) except IOError as ioerr: print('File error:'+str(ioerr)) return(None) 运行: sarah = get_coach_data_new2("sarah2.txt") print(sarah.name+"'s fastest times are "+str(sarah.top3())) 运行结果: Sarah Sweeney's fasters times are ['2.18', '2.21', '2.22']