您的位置:首页 > 编程语言 > Python开发

六、定制数据对象(Python的面向对象) ----- 打包代码与数据

2015-11-02 16:30 555 查看
创建Python字典

python字典即为键值对,相当于Java中的map,其创建的两种形式:

a = {}     # 普通方式
b = dict()  # 使用工厂函数


字典的赋值与访问

#创建字典
>>> cleese['Name'] = 'John Cleese'
>>> cleese['Occupations'] = ['actor','comedian','writer','film producer']
>>> palin = {'Name':'Michael Palin','Occupations':['comedian','actor','writer','tv']}

#访问
>>>palin['Name']
'Michel Palin'
>>>cleese['Occupations'][-1]  #使用数字来访问存储在一个特定字典键位置上的列表项。可以把这认为是‘索引串链’,从右向左读作:“……与Occupations关联的列表的最后一项……”


关于字典,重点是它会维护关联关系,而不是顺序!

Python的面向对象:定义一个类

class Athlete:                        #Python中没有new关键字,可以用__init__()方法定制对象的初始化状态
def __init__(self):
#初始化对象的代码放这里

a = Athlete()   #创建对象实例


init()方法中 self参数的重要性

在处理 a = Athlete() 这行代码时,Python会转化为如下调用: Athlete().__init__(a) , 此时a对应 __init__(self)中的self,此时Python解释器就会知道方法调用要应用到哪个对象实例。

每个方法的第一个参数都是self

Python要求每个方法的第一个参数为调用对象实例,即每个方法的第一个参数都必须是self

示例代码:

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):           #第5章最后一题,返回3个最快时间,别忘了这里的self参数
return(sorted(set([sanitize(t) for t in self.times]))[0:3])

def get_coach(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())) #调用top3()方法,将结果显示在屏幕上之前,先把结果转换为一个字符串


继承Python内置的list --- 如何继承Python的内置类

class NamedList(list):       #创建一个NamedList类,新类将继承list类
def __init__(self,a_name):
list.__init__([])    #初始化所派生的类,然后把参数赋至属性
self.name = a_name


这样NamedList就可以使用list的内置方法了 如 NamedList().append("xxx")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: