python定製資料物件

麼麼麼meme發表於2017-11-10

james2.txt: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
1、使用字典關聯資料
字典是一個內建的資料結構(內建於Python中),允許將資料與鍵而不是數字關聯。這樣可以使記憶體中的資料與實際資料的結構保持一致。
建立字典的兩種方式:
①cheese={}
②cheese=dict()

def open_file(file_name):
    try:
            with open(file_name) as data:
                    time_items= data.readline().strip().split(',')
                    james_data={}
                    james_data['Name']=time_items.pop(0)
                    james_data['Dob']=time_items.pop(0)
                    james_data['Times']=str(sorted(set(time_format(each_item) for each_item in time_items))[0:3])
                    return james_data
    except IOError as err:
        print('File error:'+str(err))

def time_format(time_item):
        if '-' in time_item:
            splits='-'
        elif ':' in time_item:
            splits=':'

        else:
            return time_item
        (mins,secs)=time_item.split(splits)
        return(mins+'.'+secs)
james_data=open_file(r'C:\Users\Administrator\Desktop\HeadFirstPython\chapter6\hfpy_ch6_data\james2.txt')

print(james_data['Name']+"'s fastest times are:"+james_data['Times'])

2、將程式碼及其資料打包在類中
使用class定義類。每個定義的類都有一個特殊的方法,名為_ init _(),可以利用這個方法控制如何初始化物件。
①類的定義基本形式如下
class Athlete:
def _ init _(self):
#The code to initialize a “Athlete”object.

注:init前面和後面分別有兩個下劃線
②建立物件例項
a=Athlete()
與C++不同,Python中沒有定義建構函式”new”的概念。Python會為你完成物件構建,然後你可以使用_ init _()方法定製物件的初始狀態。
③self的重要性
定義一個類時,實際上是在定義一個定製工廠函式,然後可以在你的程式碼中使用這個工廠函式建立例項:
a=Athlete()
Python處理這行程式碼時,它把工廠函式呼叫轉換為一下呼叫、明確了類、方法和所處理的物件例項:
Athlete()._ init() _(a)
a:物件例項的目標識別符號
④目標識別符號賦至self引數
這是一個非常重要的賦值,如果沒有這個賦值,python直譯器無法得出方法呼叫要應用到哪個物件例項。注意,類程式碼設計為在所有物件例項間共享:方法是共享的,而屬性不共享。self引數可以幫助標識要處理哪個物件例項的資料。

⑤每個方法的第一個引數都是self
你寫的程式碼 Python執行的程式碼
d=Athlete(“Holy Grail”) Athlete._ init _(d,”Holy Grail”)
d.how_big() Athlete.how_big(d)

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([santize(each_time)for each_time in self.times]))[0:3])
    def add_time(self,time_value):
     self.times.append(time_value)
    def add_times(self,list_of_times):
     self.times.extend(list_of_times)
def get_coach_data(filename):
    try:
        with open(filename) as f:
            data=f.readline()
        temp1=data.strip().split(',')
        return Athlete(temp1.pop(0),temp1.pop(0),temp1)
    except IOError as err:
        print('File error:'+str(err))
        return(None)
def santize(time_item):
        if '-' in time_item:
            splits='-'
        elif ':' in time_item:
            splits=':'

        else:
            return time_item
        (mins,secs)=time_item.split(splits)
        return(mins+'.'+secs)

james=get_coach_data(r'C:\Users\Administrator\Desktop\HeadFirstPython\chapter6\hfpy_ch6_data\james2.txt')

print(james.name+"'s fastest times are:"+str(james.top3()))

ahh=Athlete('Ahh')
ahh.add_time('4.0')
ahh.add_times(['4.0','2.0','5.0'])
print(ahh.top3())

3、繼承Python內建的list
class NamedList(list):
def _ init _(self,a_name):
list._ init _([])//初始化所派生的類
self.name=a_name//把引數賦至屬性
這裡寫圖片描述

class AthleteList(list):
    def __init__(self,a_name,a_dob=None,a_times=[]):
        list.__init__([])
        self.name=a_name
        self.dob=a_dob
        self.extend(a_times)
    def top3(self):
        return(sorted(set([santize(each_time)for each_time in self]))[0:3])

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data=f.readline()
        temp1=data.strip().split(',')
        return Athlete(temp1.pop(0),temp1.pop(0),temp1)
    except IOError as err:
        print('File error:'+str(err))
        return(None)
def santize(time_item):
        if '-' in time_item:
            splits='-'
        elif ':' in time_item:
            splits=':'

        else:
            return time_item
        (mins,secs)=time_item.split(splits)
        return(mins+'.'+secs)
jpp=AthleteList('Jinpp')
jpp.append('4.0')
jpp.extend(['4.0','2.0','5.0'])
print(jpp.top3())
class AthleteList(list):
    def __init__(self,a_name,a_dob=None,a_times=[]):
        list.__init__([])
        self.name=a_name
        self.dob=a_dob
        self.extend(a_times)
    def top3(self):
        return(sorted(set([santize(each_time)for each_time in self]))[0:3])

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data=f.readline()
        temp1=data.strip().split(',')
        return AthleteList(temp1.pop(0),temp1.pop(0),temp1)
    except IOError as err:
        print('File error:'+str(err))
        return(None)
def santize(time_item):
        if '-' in time_item:
            splits='-'
        elif ':' in time_item:
            splits=':'

        else:
            return time_item
        (mins,secs)=time_item.split(splits)
        return(mins+'.'+secs)

james=get_coach_data(r'C:\Users\Administrator\Desktop\HeadFirstPython\chapter6\hfpy_ch6_data\james2.txt')

print(james.name+"'s fastest times are:"+str(james.top3()))

相關文章