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

《Head First Python》笔记 第六章 定制数据对象

2013-04-05 21:12 846 查看

6. Custom Data Objects: Bundling code with Data

将要处理的数据如下:

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

第一个逗号前为姓名,第二个为生日,后面为时间,目的:抽取3个最快时间。

用前面章节的内容实现:



pop()
方法从指定的列表位置删除并返回一个数据项。

Use a dictionary to associate data

Dictionary(a built-in data structure)类似于Java中的Map,提供键值对方式存储数据。

创建dictionary方式:

创建空字典(两种方式):



元素可以在初始化的时候添加,也可以直接添加(不先创建空字典),可动态扩大:



与list不一样,dictionary不会维持插入的顺序,重点是它会维护关联关系,而不是顺序。

修改开头的代码:



Bundle your code and its data in a class

跟其它语言的类一个意思

Python uses
class
to create objects. Every defined class has a special method called
__init__()
, which allows you to control how objects are initialized:



创建类的对象实例(没有“new”):

a = Athlete()

将会转换为调用init方法(a为对象实例的目标标识符):

Athlete().__init__(a)

The target identifer is assigned to the self argument.

Every method's first argument is self

类中定义的每个方法都必须提供self(总是指向当前对象实例)作为第一个参数。

扩展Athlete类:



使用:
  



下面是个例子:



类定义后,属性可以动态添加,但是不能对不存在的属性进行访问:



将使用字典修改为使用类:



Inherit from Python’s built-in list

Python中的类可以继承build-in类,也可以继承自定义的类。Python支持多重继承。



修改Athlete类继承自list:



if you save your AthleteList class to a file called athletelist.py, you can import the into your code using this line of code:

from athletelist import AthleteList

跟模块中函数的导入一样:

from module import function
from module import class
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: