Python 定制类与其对象的创建和应用
1.创建新类Athlete,创建两个唯一的对象实例sarah james,他们会继承Athlete类的特性
>>> class Athlete:
def __init__(self,a_name,a_dob=None,a_times=[]):
self.name=a_name
self.dob=a_dob
self.times=a_times >>> sarah=Athlete('Sarah Sweeney','2002-07-02',['2:58','2.34','1.56'])
>>> james=Athlete('James Jone')
>>> type(sarah)
<class '__main__.Athlete'>
>>> type(james)
<class '__main__.Athlete'>
>>> sarah
<__main__.Athlete object at 0x02DAB970>
>>> james
<__main__.Athlete object at 0x02A29990>
>>> sarah.name
'Sarah Sweeney'
>>> james.name
'James Jone'
>>> sarah.dob
'2002-07-02'
>>> james.dob
>>> sarah.times
['2:58', '2.34', '1.56']
>>> james.times
[]
>>>
2. 类及其对象的应用:senitize不变,定义类Athlete和两个子方法__init__与top3。通过get_coach_data函数进行调用
def senitize(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) 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([senitize(t) for t in self.times]))[0:3]) def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
user=data.strip().split(',')
userob=Athlete(user.pop(0),user.pop(0),user)
print(userob.name+"'s fastest times are:" + str(userob.top3()))
except IOError as ioerr:
print('File error' +str (ioerr))
return (None) get_coach_data('sarah2.txt')
get_coach_data('james2.txt')
get_coach_data('mikey2.txt')
get_coach_data('julie2.txt') ========== RESTART: C:/Users/eric/Documents/Python/kelly/kelly2.py ==========
Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']
James Lee's fastest times are:['2.01', '2.16', '2.22']
Mikey McManus's fastest times are:['2.22', '2.31', '2.38']
Julie Jones's fastest times are:['2.11', '2.23', '2.59']
3.添加2个新的方法给Athlete类,并调用测试
def senitize(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) 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([senitize(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) vera=Athlete('VeraName')
vera.add_time('1.31')
print('Object name is:', vera.name)
print(vera.name+"'s top3 is: " + str(vera.top3()))
vera.add_times(['2.12','3.44','3.33'])
print(vera.name+"'s top3 is: " + str(vera.top3()))
========== RESTART: C:/Users/eric/Documents/Python/kelly/kelly3.py ==========
Object name is: VeraName
VeraName's top3 is: ['1.31']
VeraName's top3 is: ['1.31', '2.12', '3.33']
>>>
Python 定制类与其对象的创建和应用的更多相关文章
- Python定制类(进阶6)
转载请标明出处: http://www.cnblogs.com/why168888/p/6411919.html 本文出自:[Edwin博客园] Python定制类(进阶6) 1. python中什么 ...
- python定制类(1):__getitem__和slice切片
python定制类(1):__getitem__和slice切片 1.__getitem__的简单用法: 当一个类中定义了__getitem__方法,那么它的实例对象便拥有了通过下标来索引的能力. c ...
- Python初识类与对象
Python初识类与对象 类与对象 世界观角度分析类与对象 类是一个抽象的概念,而对象是一个实体的存在,对象由类创造而出,每个对象之间互相独立互不影响,一个对象可以同时拥有多个类的方法,实例化就是通过 ...
- python的类和对象2(self参数)
python的类和对象2(self参数) 1.python里面对象的方法都会有self参数,它就相当于C++里面的this指针:绑定方法,据说有了这个参数,Python 再也不会傻傻分不清是哪个对象在 ...
- python 定制类
看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让cla ...
- 类和对象的创建过程(元类,__new__,__init__,__call__)
一. type() 1.创建类的两种方式 方式一 class MyClass(object): def func(self,name): print(name) myc = MyClass() pri ...
- python 2 类与对象
1.类与对象的概念 类即类别.种类,是面向对象设计最重要的概念,从一小节我们得知对象是特征与技能的结合体,而类则是一系列对象相似的特征与技能的结合体. 那么问题来了,先有的一个个具体存在的对象(比如一 ...
- Python 【类与对象】
类与对象 把类的个例就叫做实例 (instance),可理解为“实际的例子”类是某个特定的群体,实例是群体中某个具体的个体 Python中的对象等于类和实例的集合:即类可以看作是对象,实例也可以看作是 ...
- python的类与对象
类与对象 1.什么是类 类和函数一样是程序编程的一种方式,在处理某些问题的时候类比函数更加适合让编程变得简化,在python里面函数式编程和类编程都是为了简化代码的一种编程方式,具体应用那个则由具体问 ...
随机推荐
- Git简易的命令行入门教程
简易的命令行入门教程: Git 全局设置: git config --global user.name "imsoft" git config --global user.emai ...
- java读取文件夹下所有文件并替换文件每一行中指定的字符串
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.I ...
- 安装完openfire之后打不开的解决方案
今天在http://www.igniterealtime.org/downloads/index.jsp下载了一个最新openfire for mac版 在系统的偏好设置里面是这样的.那个open A ...
- Codeforces Round #376 (Div. 2) A B C 水 模拟 并查集
A. Night at the Museum time limit per test 1 second memory limit per test 256 megabytes input standa ...
- ZOJ 1002 Fire Net
题目大意:有一个4*4的城市,其中一些格子有墙(X表示墙),在剩余的区域放置碉堡.子弹不能穿透墙壁.问最多可以放置几个碉堡,保证它们不会相互误伤. 解法:从左上的顶点开始遍历,如果这个点不是墙,做深度 ...
- 使用Spring Aop验证方法参数是否合法
先定义两个注解类ValidateGroup 和 ValidateFiled ValidateGroup .java package com.zf.ann; import java.lang.annot ...
- uva624 CD 01背包+输出最优解
link:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...
- C#部分---函数添加基本格式;
格式1:没有参数,没有返回值 (无参无返) 添加函数: /// <summary> /// 累加求和的方法,没有参数,没有返回值 /// </summary> public v ...
- leetcode 148. Sort List ----- java
Sort a linked list in O(n log n) time using constant space complexity. 排序,要求是O(nlog(n))的时间复杂度和常数的空间复 ...
- Codeforces Round #111 (Div. 2)
Codeforces Round #111 (Div. 2) C. Find Pair 题意 给\(N(N \le 10^5)\)个数,在所有\(N^2\)对数中求第\(K(K \le N^2)\)对 ...