Head First Python(定制数据对象)
2014-12-15 14:36
363 查看
新的文件格式
在上面的代码中,表示sarah的3部分相关数据分别存储在3个不同的变量中。如果选手增加,需要的变量成倍增加。
使用字典关联数据
字典是一个内置的数据结构,允许将数据(也成为“值”)与键而不是数字关联。
一次性完成字典的创建
把字典创建代码移到get_coach_data()函数中,返回一个字典而不是列表
把确定各个选手的3个最快时间的代码移到get_coach_data()函数中。
调整主代码中的函数调用,调用这个新版本的get_coach_data()函数来支持新的操作模式
这么做的好处是:
使用类有助于降低复杂性
降低复杂性意味着bug更少
bug更少意味着代码更可维护
定义一个类
在面向对象的世界里,你的代码通常称为类的方法(method),数据通常称为类的属性(attribute),实例化的数据对象称为实例(instance)。
Python要求每个方法的第一个参数为调用对象实例。
class允许通过继承现有的其他类来创建一个类,包括用list、set和dict提供的Python内置数据结构类。
在IDLE中首先派生内置list类创建一个定制列表,其有一个名为name的属性:
含有AthleteList类的新代码
<span style="font-size:18px;">Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22 </span>如果使用split()BIF把数据抽取到一个列表,第一个数据项是名字,然后是出生日期,然后是计时数据。
<span style="font-size:18px;">sarah=get_coach_data('sarah2.txt') (sarah_name,sarah_dob)=sarah.pop(0),sarah.pop(0) print(sarah_name + "'s fastest times are: " + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))</span>"pop(0)"调用将删除并返回列表的最前面的数据项。两个调用会删除前面两个数据值,并把它们赋给指定的变量。
在上面的代码中,表示sarah的3部分相关数据分别存储在3个不同的变量中。如果选手增加,需要的变量成倍增加。
使用字典关联数据
字典是一个内置的数据结构,允许将数据(也成为“值”)与键而不是数字关联。
Name ----> "Sarah Sweeney" DOB ---->"2002-6-17" Times---->[2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22]创建空字典,一种使用大括号,一种使用工厂函数创建:
>>>cleese={} >>>palin=dict() #可以一次性同时创建字典修改代码如下:
sarah=get_coach_data('sarah2.txt') sarah_data={} sarah_data['Name']=sarah.pop(0) sarah_data['DOB']=sarah.pop(0) sarah_data['Times']=sarah print(sarah_data['Name']+" 's fastest times are: "+ str(sorted(set([sanitize(t) for t in sarah_data['Times']]))[0:3]))代码还可以改进的建议:
一次性完成字典的创建
把字典创建代码移到get_coach_data()函数中,返回一个字典而不是列表
把确定各个选手的3个最快时间的代码移到get_coach_data()函数中。
调整主代码中的函数调用,调用这个新版本的get_coach_data()函数来支持新的操作模式
def get_coach_data(filename): try: with open(filename) as f: data=f.readline() templ=data.strip().split(',') return({'Name':templ.pop(0),'DOB':templ.pop(0), #一次性创建字典 'Times':str(sorted(set([sanitize(t) for t in templ]))[0:3])}) #确定前3个最快时间 except IOError as ioerr: print('File error: '+str(ioerr)) return(None) james=get_coach_data('james2.txt') #一个选手调用函数,并根据需要调用"print()"语句。 print(james['Name']+" 's fastest times are: "+james['Times'])将代码及其数据打包在类中
这么做的好处是:
使用类有助于降低复杂性
降低复杂性意味着bug更少
bug更少意味着代码更可维护
定义一个类
在面向对象的世界里,你的代码通常称为类的方法(method),数据通常称为类的属性(attribute),实例化的数据对象称为实例(instance)。
class Athlete: #类定义从class关键字开始,选取一个合适的描述性的名字 def __init__(self): #前后都有两个下划线,最后是冒号 #The code to initialize a "Athlete" object. 初始化各个对象的代码每个方法的第一个参数都是self
Python要求每个方法的第一个参数为调用对象实例。
class Athlete: def __init__(self,value=0): self.thing=value def how_big(self): return(len(self.thing))使用IDLE定义新类,创建一些对象实例
>>>class Athlete: def __init__(self,a_name.a_dob=<span style="color:#ff0000;">None</span>,a_times=<span style="color:#ff0000;">[]</span>): <span style="color:#ff0000;">#注意后两个参数的缺省值</span> self.name=a_name self.dob=a_dob self.times=a_times >>>sarah=Athlete('Sarah Sweeney','2002-6-17',['2:58','2.58','1.56]) >>>james=Athlete('James Jones')修改后的代码
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([sanitize(t) for t in self.times]))[0:3]) def get_coach_data(filename): try: with open(filename) as f: data=f.readline() templ=data.strip().split(',') return(Athlete(templ.pop(0),templ.pop(0),templ)) except IOError as ioerr: print('File error: '+str(ioerr)) return(None) james=get_coach_data('james2.txt') print(james.name+" 's fastest times are: "+str(james.top3()))向类中增加两个方法,add_time(),将一个额外的计时值追加到选手的计时数据,add_times()用一个或多个计时值扩展选手的计时数据。
def add_time(self,time_value): #伪装的append()方法和extend()方法 self.times.append(time_value) def add_times(self,time_list): self.times.extend(time_list)继承Python内置的list
class允许通过继承现有的其他类来创建一个类,包括用list、set和dict提供的Python内置数据结构类。
在IDLE中首先派生内置list类创建一个定制列表,其有一个名为name的属性:
<pre name="code" class="python">>>> class Namelist(list): def __init__(self,a_name): list.__init__([]) #初始化派生类,然后把参数赋至属性 self.name=a_name >>> johnny=Namelist("John Paul Jones") >>> type(johnny) #<span style="color:#cc0000;">"johnny"是一个"Namelist"</span> <class '__main__.Namelist'> >>> dir(johnny) #<span style="color:#cc0000;">"johnny"可以做的事情</span> ['__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__', '<span style="color:#cc0000;">append</span>', 'clear', 'copy', '<span style="color:#cc0000;">count</span>', '<span style="color:#cc0000;">extend</span>', 'index', 'insert', '<span style="color:#cc0000;">name</span>', 'pop', 'remove', 'reverse', 'sort'] >>> johnny.append("Bass Player") >>> johnny.extend(['Composer','Arranger','Musician']) >>> johnny ['Bass Player', 'Composer', 'Arranger', 'Musician'] >>> johnny.name 'John Paul Jones' >>> for attr in johnny: <span style="color:#cc0000;">#按列表处理"johnny"</span> print(johnny.name+" is a "+attr+".") John Paul Jones is a Bass Player. John Paul Jones is a Composer. John Paul Jones is a Arranger. John Paul Jones is a Musician.
含有AthleteList类的新代码
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([sanitize(t) for t in <span style="color:#cc0000;">self</span>]))[0:3])
演练新类
vera=AthleteList('Vear Vi') #<span style="color:#cc0000;">使用新的类名</span> vera.append('1.31') print(vera.top3()) vera.extend(['1.45','2.45','2,31']) print(vera.top3())
相关文章推荐
- 《head first python》——定制数据对象
- [Head First Python]6. 定制数据对象:打包代码与数据
- HeadFirstPython---------(四)第六章(定制数据对象__打包代码与数据)
- Head First Python ch_6 定制数据对象
- 《Head First Python》笔记 第六章 定制数据对象
- 【Head First Python-第六章-定制数据对象】学习笔记
- Head Frist Python 读书笔记 第六章 定制数据对象
- Head First Python 学习笔记-Chapter6:自定义数据对象:字典与类
- HeadFirstPython---------(二)第四章,持久存储,数据保存到文件
- 《head first python》——理解数据:列表排序与集合
- Head First Python 学习笔记-Chapter4:持久化--将数据写入文件
- Head First Python(推导数据)
- python系列学习四——定制数据对象
- cgi.FieldStorage()获取网页间提交的数据《Head First Python》第七章
- Python学习笔记_Chapter 6定制数据对象
- python定制数据对象
- 《Head_First_Python》 5推导数据
- 《Head First Programming》---python 4_文件和数组中的数据
- Head First Python(管理你的数据)
- Head First Python 第二章 函数模块&第三章 文件与异常&第四章 持久存储&第五章 处理数据