Head First Python(定制数据对象)

新的文件格式

<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]))
代码还可以改进的建议:

  1. 一次性完成字典的创建
  2. 把字典创建代码移到get_coach_data()函数中,返回一个字典而不是列表
  3. 把确定各个选手的3个最快时间的代码移到get_coach_data()函数中。
  4. 调整主代码中的函数调用,调用这个新版本的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'])
将代码及其数据打包在类中

这么做的好处是:

  1. 使用类有助于降低复杂性
  2. 降低复杂性意味着bug更少
  3. 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())













  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值