head first python 6 class 扩展

简介: 点击(此处)折叠或打开 #!/usr/bin/env python3 # -*- coding:utf-8 -*- import os clas...

点击(此处)折叠或打开

  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import os
  4. class athlete:
  5.     def __init__(self, athlete_name, athlete_dob=None, athlete_times=[]):
  6.         self.name = athlete_name
  7.         self.dob = athlete_dob
  8.         self.times= athlete_times
  9.     #运动员最好的3组成绩
  10.     def top3(self):
  11.         return(sorted(set([sanitize(time) for time in self.times]))[0:3])
  12.     #为运动员添加一个成绩
  13.     def add_time(self, time_value):
  14.         self.times.append(time_value)
  15.     #为运动员添加一组成绩,使用列表类型.
  16.     def add_times(self, time_list):
  17.         self.times.extend(time_list)

  18. def openfile(filename):
  19.     try:
  20.         #打开文件
  21.         with open(filename) as athlete_file:
  22.             #读取数据
  23.             data = athlete_file.readline()
  24.             value_list= data.strip().split(',')
  25.             username = value_list.pop(0)
  26.             userdob = value_list.pop(0)
  27.             usertimes= value_list
  28.             #返回实例对象
  29.             athlete_instance=athlete(username,userdob,usertimes)
  30.             return(athlete_instance)
  31.     except IOError as ioerr:
  32.         print('File error %s' % ioerr)
  33.         return(None)

  34. #处理字符,转换成m.s格式
  35. def sanitize(time_string):
  36.     if '-' in time_string:
  37.         splitter = '-'
  38.     elif ':' in time_string:
  39.         splitter = ':'
  40.     else:
  41.         return time_string
  42.     (min, sec) = time_string.split(splitter)
  43.     return (min + '.' + sec)
  44. for name in ["james", "julie", "mikey", "sarah"]:
  45.     name = openfile(name+'.txt')
  46.     print(name.name + '的三次最佳成绩是' + str(name.top3()))


  47. talen = athlete('talen')
  48. talen.add_time('3.25')
  49. talen.add_time('3.45')
  50. talen.add_times(['1.30','2.59'])
  51. print(str(talen.top3()))

t@localhost 6$ python3 kelly_c.py
James Lee的三次最佳成绩是['2.01', '2.16', '2.22']
Julie Jones的三次最佳成绩是['2.11', '2.23', '2.59']
Mikey McManus的三次最佳成绩是['2.22', '2.31', '2.38']
Sarah Sweeney的三次最佳成绩是['2.18', '2.21', '2.22']
['1.30', '2.59', '3.25']

继承list类

点击(此处)折叠或打开

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
class athlete:
    def __init__(self, athlete_name, athlete_dob=None, athlete_times=[]):
        self.name = athlete_name
        self.dob = athlete_dob
        self.times= athlete_times
    #运动员最好的3组成绩
    def top3(self):
        return(sorted(set([sanitize(time) for time in self.times]))[0:3])
    #为运动员添加一个成绩
    def add_time(self, time_value):
        self.times.append(time_value)
    #为运动员添加一组成绩,使用列表类型.
    def add_times(self, time_list):
        self.times.extend(time_list)
#使用类继承,继承内置list类
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(t) for t in self]))[0:3])

def openfile(filename):
    try:
        #打开文件
        with open(filename) as athlete_file:
            #读取数据
            data = athlete_file.readline()
            value_list= data.strip().split(',')
            username = value_list.pop(0)
            userdob = value_list.pop(0)
            usertimes= value_list
            #返回实例对象
            athlete_instance=athlete(username,userdob,usertimes)
            return(athlete_instance)
    except IOError as ioerr:
        print('File error %s' % ioerr)
        return(None)

#处理字符,转换成m.s格式
def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    (min, sec) = time_string.split(splitter)
    return (min + '.' + sec)
for name in ["james", "julie", "mikey", "sarah"]:
    name = openfile(name+'.txt')
    print(name.name + '的三次最佳成绩是' + str(name.top3()))


talen = athlete('talen')
talen.add_time('3.25')
talen.add_time('3.45')
talen.add_times(['1.30','2.59'])
print(str(talen.top3()))
ken = athletelist('ken')
#为运动员添加一个成绩
#由于继承list,不需要自己再定义添加方法,直接使用list的方法
ken.append('4.25')
#为运动员添加一组成绩,使用列表类型.
ken.extend(['4.56','6.20','5.20'])
print(ken.top3())


目录
相关文章
|
4月前
|
编译器 Linux C语言
python C语言扩展之简单扩展-使用ctypes访问C代码
python C语言扩展之简单扩展-使用ctypes访问C代码
19 0
|
5月前
|
API Python
python 详细理解 import ---- openstack自动import class 到 特定命名空间
python 详细理解 import ---- openstack自动import class 到 特定命名空间
48 0
|
6月前
|
Python Windows
Python 扩展 快捷贴士:os模块下的创建目录的方式
如果子目录创建失败或者已经存在,会抛出一个 OSError 的异常,Windows上Error 183 即为目录已经存在的异常错误。
54 0
|
25天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
61 0
|
2月前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
20 0
|
2月前
|
存储 设计模式 Python
Python中的类(Class)和对象(Object)
Python中的类(Class)和对象(Object)
32 0
|
3月前
|
开发者 Python
Python中的元编程:扩展语言的力量
【2月更文挑战第5天】本文将探讨Python中的元编程,介绍了元编程的概念和意义,并详细讨论了Python中常用的元编程技术,如装饰器、元类和动态类型。通过元编程,我们可以在不改变语言核心的情况下,扩展Python的功能和灵活性,为开发者提供更强大的工具和框架。
|
4月前
|
设计模式 Python
Python中的装饰器:优雅而强大的功能扩展工具
在Python中,装饰器是一种强大的功能扩展工具,它可以在不修改原始函数代码的情况下,动态地添加额外的功能。本文将深入探讨Python中装饰器的使用方法和应用场景,并结合实际案例详细介绍其实现原理及优雅的设计模式。
|
9月前
|
数据挖掘 Linux Python
Python学习笔记丨函数和类相关基础知识总结和易错点分享,包括def、lambda、class等
Python学习笔记丨函数和类相关基础知识总结和易错点分享,包括def、lambda、class等
|
5月前
|
安全 程序员 Python
Python-logging详解(彩色日志扩展,多进程安全等)
Python-logging详解(彩色日志扩展,多进程安全等)
50 0