[学习笔记]Head First Python 第6章 定制数据对象 打包代码和数据 6-2定义面向对象的类 定制类

# 第6章 定制数据对象 打包代码和数据

##########################################
# 定义面向对象的类 定制类
# 代码:方法(method) 数据:属性(attribute) 数据对象:实例(instance)
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 add_time(self,time_value):
        self.times.append(time_value)

    def add_times(self, list_of_times):
        self.times.extend(list_of_times)


def sanitize(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 readdata(file):
    try:
        with open(file) as datafile:
            data = datafile.readline()
        data = data.strip().split(',')  # 从字符串首尾去除不想要的空白符'/n' # 方法串联
        # (data_name, data_dob) = data.pop(0), data.pop(0)          # 元胞数组   # pop()删除指定数据并提取出来

        # templ = {Athlete.name: data.pop(0), Athlete.dob: data.pop(0),  # 字典
        #          Athlete.times: data}
        templ = Athlete(data.pop(0), data.pop(0), data)             # 类
        return templ
    except IOError as ioerr:
        print('File error:' + str(ioerr))
        return (None)


james = readdata('.\\hfpy_ch6_data\\james2.txt')
julie = readdata('.\\hfpy_ch6_data\\julie2.txt')
mikey = readdata('.\\hfpy_ch6_data\\mikey2.txt')
sarah = readdata('.\\hfpy_ch6_data\\sarah2.txt')

print(james.name + "'s fastest times are:" + str(james.top3()))
print(julie.name + "'s fastest times are:" + str(julie.top3()))
print(mikey.name + "'s fastest times are:" + str(mikey.top3()))
print(sarah.name + "'s fastest times are:" + str(sarah.top3()))

# 类的数据填充
saeah = Athlete('Sarah Sweeney', '2002-6-17', ['2:58', '2.58', '2:39'])
james = Athlete('James Jones')              # 对象实例
print(type(saeah))
print(type(james))
print(saeah)
print(james)
print(saeah.name)
print(james.name)
print(saeah.dob)
print(james.dob)
print(saeah.times)
print(james.times)

# #测试add_time 和add_times
vera = Athlete('Vera Vi')
vera.add_time('1.31')
print(vera.top3())
vera.add_times(['2.22', '1-22', '2:22'])
print(vera.top3())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值