#! usr/bin/env python
# -*- coding:utf-8 -*-
import os
os.chdir('C:\\Python34\\headfirst\\demo')
class AtheletList(list):
def __init__(self,name = None, dob = None, times = []):
list.__init__([])
self.name = name
self.dob = dob
self.extend(times)
def top3(self):
return str(sorted(set([sanitize(i) for i in self]))[0:3])
class Athelet:
def __init__(self,name = None, dob = None, times = []):
self.name = name
self.dob = dob
self.times = times
def top3(self):
return str(sorted(set(self.times))[0:3])
def add_time(self,time_str):
self.times.append(sanitize(time_str))
def add_times(self,times):
self.times.extend([sanitize(i) for i in times])
def sanitize(time_str):
if ':' in time_str:
splitter = ':'
elif '-' in time_str:
splitter = '-'
else:
return time_str
(min,sec) = time_str.split(splitter)
return (min + '.' + sec)
def get_data(filename):
try:
with open(filename) as f:
data = f.readline()
temp = data.strip().split(',')
name = temp.pop(0)
dob = temp.pop(0)
times = [sanitize(i) for i in temp]
a = Athelet(name,dob,times)
except FileNotFoundError as error:
print('File Error:' + error)
return None
return a
james = get_data('james2.txt')
print(james.name + "'s best times are:" + james.top3())
print('*'*64)
print(james.name + "'s date of birth is:" + james.dob)
print('*'*64)
print(james.name + "'s time list is:" + str(james.times))
print('*'*64)
print("Add a data to james's time list: '2-15'")
james.add_time('2-15')
print('*'*64)
print(james.name + "'s time list now is:" + str(james.times))
print('*'*64)
print("Add some datas to james's time list: '2:24','2:39','2-17'")
james.add_times(['1-59','2:24','1-48','2-17'])
print('*'*64)
print(james.name + "'s time list now is:" + str(james.times))
print('*'*64)
b = AtheletList('Dean','1992-09-24',['dawdw','daddfrg','grdgrd'])
print(b.name)
詳細內(nèi)容參見:
python中的繼承