1. 程式人生 > >Head First Python-python面向物件

Head First Python-python面向物件

與大多數其他的程式語言一樣,Python容許建立並定義面向物件的類,類可以將程式碼與程式碼處理的資料相關聯。

對於更加複雜的資料,一般的列表已經不能滿足需求了。

 我們可以使用字典dict將資料值與鍵相關聯。

1,使用dict來完成處理

相關處理程式碼如下:

#DICT

def sanitize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        
return time_string (mins,secs)=time_string.split(spliter) return mins+'.'+secs def get_coach_data(filename): james_data = {} try: with open(filename) as f: data=f.readline() temp_data=data.strip().split(',') #f_data=[sanitize(i) for i in temp_data]
james_data = {'Name':temp_data.pop(0),'Bir':temp_data.pop(0),'Times':str(sorted([sanitize(i) for i in temp_data])[0:3])} return james_data except IOError as Ierror: print('read file error: '+str(Ierror)) return None james=get_coach_data('./data/james2.txt
') print(james['Name']+"'s fastest times are: "+james['Times'])

2,使用python類:

在面向物件的世界裡,程式碼通常稱為類的方法,資料通常稱為類的屬性。例項化資料物件通常稱為例項。

#class

class Athlete(object):
    def __init__(self,name,bir=None,times=[]):
        self.name=name
        self.bir=bir
        self.times=times

    def top3(self):
        return  sorted(set([sanitize(i) for i in self.times]))[0:3]

    def add_time(self,a_time):
        self.times.append(a_time)

    def add_times(self,b_time):
        self.times.extend(b_time)

def sanitize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    (mins,secs)=time_string.split(spliter)
    return mins+'.'+secs

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data=f.readline()
            temp_data=data.strip().split(',')
        return Athlete(temp_data.pop(0),temp_data.pop(0),temp_data)
    except IOError as ioerror:
        print('file open fail:' + str(ioerror))
        return  None

james=get_coach_data('./data/james2.txt')
james.add_times(['1-1','1:2'])
print(james.name+"'s fastest times are: "+str(james.top3()))