python中head_Python(Head First)学习笔记:六

6 定制数据对象:数据结构自定义

打包代码与数据

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

julie2.txt:

Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21,3.01,3.02,2:59

mikey2.txt:

Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38,2:40,2.22,2-31

sarah2.txt :

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

现在要通过函数get_coach_data()来读取sarah2.txt,并完成排序的工作,代码如下:

>>> 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]))

输出:Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']

上面用到了pop(0),这个方法会删除并返回最前面的数据项;两个pop(0)调用则会删除前两个数据值,并把它们复制给指定的变量。

以上方法适用于数据较少的情况,如果数据量大了,就需要引入字典关联。

使用字典关联数据

字典是一个内置的数据结构(内置与Python中),允许将数据与键关联,这个键和数据库的键是相同的概念。

这样可以使内存中的数据与实际数据的结构保持一致,其他语言中可能称为:映射,散列,关联数组。

注:每个字典都有一个Name和一个Occupations列表列表。

有两种方法可以创建字典:

一:使用大括号创建;

如:cleese = {}

二:使用工厂函数创建;

如:palin =dict()

此外,可用type(cleese),type(palin)来查看字典的类型。

>>> cleese['Name']='John Cleese' #创建Name列表

>>> cleese['Occuptions']=['actor','comedian','writer','film producer'] #创建Occuptions列表

>>> palin={'Name':'Michael Palin','Occupations':['comedian','actor','writer','tv']} #创建字典内容,需注意palin字典是一次性同时创建的

>>> palin['Name']

'Michael Palin'

>>> cleese['Occuptions']

['actor', 'comedian', 'writer', 'film producer']

>>> cleese['Occuptions'][-1]

'film producer'

接下来,给palin和cleese增加出生地址信息:

>>> palin['Birthplace']="Broomhill,Sheffield,Endland"

>>> cleese['Birthplace']="Weston-super-Mare,North somerset,England"

>>> palin

{'Birthplace': 'Broomhill,Sheffield,Endland', 'Occupations': ['comedian', 'actor', 'writer', 'tv'], 'Name': 'Michael Palin'}

>>> cleese

{'Birthplace': 'Weston-super-Mare,North somerset,England', 'Occuptions': ['actor', 'comedian', 'writer', 'film producer'], 'Name': 'John Cleese'}

接下来,修改方法get_coach_data()方法,加入字典的创建和使用:

ContractedBlock.gif

ExpandedBlockStart.gif

>>> defget_coach_data1(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])})exceptIOError as ioerr:print('File error:'+str(ioerr))return(None)>>> james=get_coach_data1('james2.txt')>>> print(james['Name']+"'s fastest times are:"+ james['Times'])

James Lee's fastest times are:['2.01','2.16','2.22']

>>> julie=get_coach_data1('julie2.txt')>>> print(julie['Name']+"'s fastest times are:"+ julie['Times'])

Julie Jones's fastest times are:['2.11','2.23','2.59']

>>> mikey=get_coach_data1('mikey2.txt')>>> print(mikey['Name']+"'s fastest times are:"+ mikey['Times'])

Mikey McManus's fastest times are:['2.22','2.31','2.38']

>>> print(sarah['Name']+"'s fastest times are:"+ sarah['Times'])>>> sarah=get_coach_data1('sarah2.txt')>>> print(sarah['Name']+"'s fastest times are:"+ sarah['Times'])

Sarah Sweeney's fastest times are:['2.18','2.21','2.22']

View Code

将代码及其数据打包在类中

这样做的好处有:1使用类有助于降低复杂性;

2降低复杂性意味着bug更少;

3bug更少意味着代码更好维护;

关于Python的类

Python遵循标准的面向对象编程模型,一旦定义了类,就可以用类来创建数据对象,这个对象实例可以继承类的特性。

通常代码称为类的方法,数据通常称为类的属性,实例化的数据对象称为实例。

使用class定义类

基本格式:class 类名(继承类):

def __init__(self,参数1,参数2,....,列表1,列表2....):

初始化...

类方法1....

类方法2....

................

ContractedBlock.gif

ExpandedBlockStart.gif

>>> defsanitize(time_string):if '-'intime_string:

splitter='-'

elif ':'intime_string:

splitter=':'

else:return(time_string)

(mins,secs)=time_string.split(splitter)return(mins+'.'+secs)>>> classAthleteList(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)deftop3(self):return(sorted(set({sanitize(t)for t in self}))[0:3])>>> defget_coach_data(filename):try:

with open(filename)as f:

data=f.readline()

templ=data.strip().split(',')return(AthleteList(templ.pop(0),templ.pop(0),templ))exceptIOError as ioerr:print('File error:'+str(ioerr))return(None)>>> james=get_coach_data('james2.txt')>>> julie=get_coach_data('julie2.txt')>>> mikey=get_coach_data('mikey2.txt')>>> sarah=get_coach_data('sarah2.txt')>>> print(james.name + "'s fastest times are:"+str(james.top3()))

James Lee's fastest times are: ['2.01','2.16','2.22']

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

Julie Jones's fastest times are: ['2.11','2.23','2.59']

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

Mikey McManus's fastest times are: ['2.22','2.31','2.38']

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

Sarah Sweeney's fastest times are: ['2.18','2.21','2.22']

View Code

总结:

Python术语:

1 字典:Python的一种内置数据结构,允许将数据值与键关联;

键:字典中查找的部分,值:字典中的数据部分。

2 self:一个方法参数,总是指向当前对象实例。

方法:

1 通过dict()或{}可以创建一个空字典;

2 访问一个名为persion的字典与Name关联的值,可以用person['Name'];

3 字典和列表和集合有类似的地方,可以随新数据的增加而动态扩展;

4 可以用class关键字定义一个类;

5 类的方法和函数定义基本相同,用def关键字;

6 类的属性就像是对象实例中的变量;

7 可通过在类中定义__init__()方法来初始化对象实例;

8 类中定义的每个方法必须提供self作为第一个参数;

9 类中每一个数据前面都必须有self作为第一个参数,从而将数据与实例关联;

10 类可以从零开始构建,也可以从Python的内置类或从其他定制类继承;

11 类可以放到一个Python模块中,并上传到PyPI。

------------------------------------------------The End of Sixth Chapter-----------------------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值