1. 程式人生 > >【七】定制數據對象

【七】定制數據對象

eof 對象 time out utf-8 doc com 復制 .cn

一:編寫程序

現如今有一組新的秒表數據,需要對其數據進行提取

sarah.txt

sara,2002-9-9,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55

1.將sarah.txt中的名字與成績打印出來(使用讀取文件的方式)

#coding=utf-8
#打印出秒表數據的姓名與前三列的成績
def get_file(filename):
    try:
        with open(filename) as f:
            data=f.readline().strip().split(",")
            return
data except IOError as e: raise e def qxsj(time_string): if "-" in time_string: splitter="-" elif ":" in time_string: splitter=":" else: return time_string (fen,miao)=time_string.strip().split(splitter) return(fen+"."+miao) open_file=get_file("
D:\pydj\sarah.txt") #移除前兩列的數據 user_name,user_sr=open_file.pop(0),open_file.pop(0) print(open_file) print(user_name,user_sr) print(user_name+"’fastest times are:"+str(sorted(set([qxsj(i) for i in open_file]))[0:3]))

打印結果:技術分享

技術分享

完善代碼思路:

  1. 一次性完成字典的創建
  2. 把字典創建代碼一到get_file()函數中,返回一個字典而不是列表
  3. 把確定各個選手的3個最快時間的代碼移到get_file()函數中
  4. 調整主代碼中的函數調用,調用這個新版本的get_file()函數來支持新的操作模式

mikey.txt

mikey test,2000-2-2,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38

2.將sarah.txt中的名字與成績打印出來(使用字典的方式)

#coding=utf-8
def get_file(filename):
    try:
        with open(filename) as f:
            data=f.readline().strip().split(",")
            #返回一個字典,字典中將各個數據提取出來
            return({
                "Name":data.pop(0),
                "DOB":data.pop(0),
                "Times":str(sorted(set([qxsj(i) for i in data]))[0:3])
            })
    except IOError as e:
        raise e
def qxsj(time_string):
    if "-" in time_string:
        splitter="-"
    elif ":" in time_string:
        splitter=":"
    else:
        return time_string
    (fen,miao)=time_string.strip().split(splitter)
    return(fen+"."+miao)
#sarch的記錄
sarch_file=get_file("D:\pydj\sarah.txt")
print(sarch_file["Name"]+"’fastest times are:"+sarch_file["Times"])
#mikey的記錄
mikey_file=get_file("D:\pydj\mikey.txt")
print(mikey_file["Name"]+"’fastest times are:"+mikey_file["Times"]) 

打印結果:

C:\Python27\python.exe D:/pydj/ex5.py
sara’fastest times are:[2.18, 2.25, 2.39]
mikey test’fastest times are:[2.22, 2.38, 2.49]

Process finished with exit code 0

二:使用class定義類

技術分享

創建對象實例

a=Athlete()
b=Athlete()
c=Athlete()
d=Athlete()
  • 小括號告訴python要創建一個新的“Athlete”對象,然後復制給一個變量
  • 所有這些變量都是唯一的,類型都是Athlete

self的重要性

技術分享

每個方法的第一個參數都是self

技術分享

技術分享

#定義一個a類
In [20]: class a:
    ...:     def __init__(self,a_name,a_dob=None,a_times=[]):
    ...:         self.name=a_name
    ...:         self.dob=a_dob
    ...:         self.times=a_times
    ...:    
#實例化該類     
In [21]: sarah=a("sarah","200-2-2",["2:55","2.3","9-6"])
#查看sarah的類型,為a類
In [22]: type(sarah)
Out[22]: __main__.a
In [23]: sarah
Out[23]: <__main__.a at 0x7f2df2262a20>
In [24]: sarah.name
Out[24]: sarah
In [25]: sarah.dob
Out[25]: 200-2-2
In [26]: sarah.times
Out[26]: [2:55, 2.3, 9-6]

3.將sarah.txt中的名字與成績打印出來(使用類的方式)

#coding=utf-8
#編寫代碼來定義Athlete類
#除了__init__()方法外,還要定義一個新方法top3(),調用這個方法會返回最快的3個時間
#要調整dakaiwenjian()函數,返回Athlete對象而不是字典
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 str(sorted(set([fenge(i) for i in self.times]))[0:3])
def dakaiwenjian(filename):
    try:
        with open(filename,"r") as f:
            data=f.readline().strip().split(",")
            return(Athlete(a_name=data.pop(0),a_dob=data.pop(0),a_times=data))
    except IOError as e:
        raise e
def fenge(time_string):
    if "-" in time_string:
        splitter="-"
    elif ":" in time_string:
        splitter=":"
    else:
        return time_string
    (fen,miao)=time_string.strip().split(splitter)
    return(fen+"."+miao)
#sarch的記錄
sarch_file=dakaiwenjian("D:\pydj\sarah.txt")
print(sarch_file.name+"’fastest times are:"+sarch_file.top3())
#mikey的記錄
mikey_file=dakaiwenjian("D:\pydj\mikey.txt")
print(mikey_file.name+"’fastest times are:"+mikey_file.top3())

打印結果:

C:\Python27\python.exe D:/pydj/ex8.py
sara’fastest times are:[2.18, 2.25, 2.39]
mikey test’fastest times are:[2.22, 2.38, 2.49]

Process finished with exit code 0

4.向你的類增加兩個方法,一個為add_time(),將一個額外的計時值追加到選手的計時數據。第二個方法add_times()會用一個或多個計時值(提供一個列表)來擴展一個選手的計時數據

#coding=utf-8
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 str(sorted(set([fenge(i) for i 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 dakaiwenjian(filename):
    try:
        with open(filename,"r") as f:
            data=f.readline().strip().split(",")
            return(Athlete(a_name=data.pop(0),a_dob=data.pop(0),a_times=data))
    except IOError as e:
        raise e
def fenge(time_string):
    if "-" in time_string:
        splitter="-"
    elif ":" in time_string:
        splitter=":"
    else:
        return time_string
    (fen,miao)=time_string.strip().split(splitter)
    return(fen+"."+miao)
#sarch的記錄
sarch_file=dakaiwenjian("D:\pydj\sarah.txt")
#為sarch增加一個秒表時間
sarch_file.add_time("1.11")
print(sarch_file.name+"’fastest times are:"+sarch_file.top3())
#mikey的記錄
mikey_file=dakaiwenjian("D:\pydj\mikey.txt")
print(mikey_file.name+"’fastest times are:"+mikey_file.top3())

打印結果:

C:\Python27\python.exe D:/pydj/ex8.py
sara’fastest times are:[‘1.11‘, ‘2.18‘, ‘2.25‘]
mikey test’fastest times are:[‘2.22‘, ‘2.38‘, ‘2.49‘]

Process finished with exit code 0

三:繼承類

5.繼承python內置的list

In [28]: class Namelist(list):
    ...:     def __init__(self,a_name):
    ...:         list.__init__([])
    ...:         self.name=a_name
    ...:         
#實例化類
In [29]: huahua=Namelist("qwe")
In [30]: type(huahua)
Out[30]: __main__.Namelist
#該實例的方法
In [31]: dir(huahua)
Out[31]: 
[__add__,
 __class__,
 __contains__,
 __delattr__,
 __delitem__,
 __dict__,
 __dir__,
 __doc__,
 __eq__,
 __format__,
 __ge__,
 __getattribute__,
 __getitem__,
 __gt__,
 __hash__,
 __iadd__,
 __imul__,
 __init__,
 __iter__,
 __le__,
 __len__,
 __lt__,
 __module__,
 __mul__,
 __ne__,
 __new__,
 __reduce__,
 __reduce_ex__,
 __repr__,
 __reversed__,
 __rmul__,
 __setattr__,
 __setitem__,
 __sizeof__,
 __str__,
 __subclasshook__,
 __weakref__,
 append,
 clear,
 copy,
 count,
 extend,
 index,
 insert,
 name,
 pop,
 remove,
 reverse,
 sort]
In [32]: huahua
Out[32]: []
#append方法
In [33]: huahua.append("one")
In [34]: huahua
Out[34]: [one]
#extend方法
In [35]: huahua.extend(["two","three"])
In [36]: huahua
Out[36]: [one, two, three]

6.把原有的Athlete類的代碼刪除,寫一個新的Atheletelist類,讓它繼承內置的list類,然後進行測試

#coding=utf-8
class  Athletelist(list):
    def __init__(self,a_name,a_dob=None,a_times=[]):
        list.__init__(self)
        self.name=a_name
        self.dob=a_dob
        #因為該類繼承了list,所以不需要將a_times在重新賦值,直接將a_times,extend
        self.extend(a_times)
    #前三名成績
    def top3(self):
        return str(sorted(set([fenge(i) for i in self]))[0:3])
def dakaiwenjian(filename):
    try:
        with open(filename,"r") as f:
            data=f.readline().strip().split(",")
            return(Athletelist(a_name=data.pop(0),a_dob=data.pop(0),a_times=data))
    except IOError as e:
        raise e
def fenge(time_string):
    if "-" in time_string:
        splitter="-"
    elif ":" in time_string:
        splitter=":"
    else:
        return time_string
    (fen,miao)=time_string.strip().split(splitter)
    return(fen+"."+miao)
#sarch的記錄
sarch_file=dakaiwenjian("D:\pydj\sarah.txt")
#為sarch增加一個秒表時間
print(sarch_file.name+"’fastest times are:"+sarch_file.top3())
#mikey的記錄
mikey_file=dakaiwenjian("D:\pydj\mikey.txt")
print(mikey_file.name+"’fastest times are:"+mikey_file.top3())

打印結果:

C:\Python27\python.exe D:/pydj/ex8.py
sara’fastest times are:[2.18, 2.25, 2.39]
mikey test’fastest times are:[2.22, 2.38, 2.49]

Process finished with exit code 0

【七】定制數據對象