python系列学习四——定制数据对象

1. 使用字典关联数据

    字典是python的一个内置数据结构,允许将数据与键而不是数字关联,这样可以使内存中的数据与实际数据的结构保持一致。字典在其他编程语言还有不同的名字,比如“映射”、“散列”、“关联数组”等。

1)创建空字典


2)给字典增加数据


与列表不同,python字典不会维持插入的顺序,字典重点维护的是关联关系,而不是顺序。


2. 使用类将代码与其数据打包

优点:使用类有利于降低复杂性;降低复杂性意味着bug更少;bug更少意味着代码更可维护;

1)定义类

在面向对象世界里,代码通常称为类的方法(method),而数据通常称为类的属性(attribute),实例化的数据对象则称为实例(instance)。

class Athlete:
    def __init__(self): # self为对象实例的目标标识符
        #The code to initialize a "Athelte" object
        ...
2) 创建对象实例
a = Athlete()
b = Athlete()
c = Athlete()
3)每个方法的第一个参数都是self

Python要求类中每个方法的第一个参数都是self:

class Athlete:
    def __init__(self, value=0):
        self.thing = value
    def how_big(self):
        return len(self.thing)

d = Athlete('Holy Grail')
print d.how_big()

 小应用: 
#!/usr/local/bin/python
#coding=utf-8

def sanitize(time_string):
    """Handling with data format of time_string"""
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    (mins, secs) = time_string.split(splitter)
    return mins + '.' + secs

def get_coach_data(filename):
    """return a Athlete class of coach data"""
    try:
        with open(filename) as v_file:
            data = v_file.readline().strip().split(',')
        return Athlete(data.pop(0), data.pop(0), data)
    except IOError as err:
        print 'File error: ' + str(err)
        return None

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(item) for item in self.times]))[0:3]
    def add_time(self, a_time):
        self.times.append(a_time)
    def add_times(self, a_times):
        self.times.extend(a_times)

james = get_coach_data('james2.txt')
print james.name + "'s fastest times are: " + str(james.top3())

# for test
vera = Athlete('Vera Vi')
vera.add_time('1.31')
print vera.top3()
vera.add_times(['2.22', '1.21', '2.32'])
print vera.top3()

3. 类的继承

# 提供一个类名,新类将派生这个类
class NamedList(list): 
    def __init__(self, a_name):
        # 初始化所派生的类
        list.__init__([])
        self.name = a_name

可以看到,该类可以做到列表所做的所有事情,还可以在name属性中存储数据。

小实例:

#!/usr/local/bin/python
#coding=utf-8

def sanitize(time_string):
    """Handling with data format of time_string"""
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    (mins, secs) = time_string.split(splitter)
    return mins + '.' + secs

def get_coach_data(filename):
    """return a Athlete class of coach data"""
    try:
        with open(filename) as v_file:
            data = v_file.readline().strip().split(',')
        return AthleteList(data.pop(0), data.pop(0), data)
    except IOError as err:
        print 'File error: ' + str(err)
        return None

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(item) for item in self]))[0:3]

james = get_coach_data('james2.txt')
print james.name + "'s fastest times are: " + str(james.top3())

# for test
vera = AthleteList('Vera Vi')
vera.append('1.31')
print vera.top3()
vera.extend(['2.22', '1.21', '2.32'])
print vera.top3()

小结:

1)使用dict()工厂函数或使用{}可以创建一个空字典

2)类似于列表和集合,Python的字典会随着新数据增加到这个数据结构中而动态变大

3)类方法与函数的定义基本相同,使用def关键字定义

4)类属性就像是对象实例中的变量

5)类中定义__init__()方法来初始化对象实例

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

7)类中的每个属性前面都必须有self,从而将数据与其实例关联

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值