python定制数据对象

来源:互联网 发布:表白网页制作软件 编辑:程序博客网 时间:2024/05/21 22:08

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()))
原创粉丝点击