一个简单的时间类的定制
2016-05-01 12:18
465 查看
这是在看《python核心编程》的第十三章的一个习题,自己全部实现了它的功能要求,学会了__add__、__iadd__、__radd__的使用方法,iadd是自加,等同于i += j;而radd是右边相加,就是a + b的时候a没有add的方法,才会调用b的radd方法,使用起来就简单了,无非是对应的属性相加或者相减,关键是对相加或相减的结果进行恰当的处理;还有就是__str__ 和__repr__的不同使用,str是在用print的时候输出的值,而repr执行实例的时候输出值,也就是输出的是哪个实例如Time60(‘12:05’)这样的输出才是合法的,下面是具体的代码:
class Time60(object): def __init__(self, hr = 0, min = 0): self.hr = hr if not isinstance(self.hr, int): raise TypeError, 'input int value' if self.hr < 0: raise ValueError, 'input 0 - 24 integtor' self.min = min if not isinstance(self.min, int): raise TypeError, 'input int value' if self.min < 0: raise ValueError, 'input 0 - 60 integtor' if self.min > 60: self.hr = self.hr + self.min/60 self.min = self.min%60 def __str__(self): return '%.2d:%.2d'%(self.hr, self.min) def __repr__(self): return "%s('%.2d':'%.2d')"%(self.__class__.__name__, self.hr, self.min) def __add__(self, other): if not isinstance(other, Time60): raise TypeError, 'please input Time60 instance' return self.__class__(self.hr + other.hr, self.min + other.min) def __sub__(self, other): if not isinstance(other, Time60): raise TypeError, 'please input Time60 instance' if self.min < other.min: self.hr -= 1 self.min = self.min + 60 return self.__class__(self.hr - other.hr, self.min - other.min) def __cmp__(self, other): if not isinstance(other, Time60): raise TypeError, 'please input Time60 instance' return cmp(self.hr, other.hr) or cmp(self.min, other.min) def __iadd__(self, other): if not isinstance(other, Time60): raise TypeError, 'please input Time60 instance' self.hr += other.hr self.min += other.min return self @classmethod def userTime(cls, time): if isinstance(time, (list, tuple)): hr = int(time[0]) min = int(time[1]) return cls(hr, min) elif isinstance(time, dict): hr = int(time.get('hr')) min = int(time.get('min')) return cls(hr, min) elif isinstance(time, (unicode, basestring)): import re match = re.match(r'^(\d{2}):(\d{2}|\d{1})', time) hr = int(match.group(1)) min = int(match.group(2)) return cls(hr, min) def __nonzero__(self): return int(self.hr) or int(self.min) if __name__ == '__main__': mon = Time60() thu = Time60(10, 30) fri = Time60(8, 45) thu + fri thu - fri thu > fri sat = Time60.userTime((10, 30)) sun = Time60.userTime({'hr': 12, 'min': 54}) two = Time60.userTime('11:30') hol = Time60.userTime('12:5')
相关文章推荐
- hdoj 5676 ztr loves lucky numbers 【二分】
- hdoj 5675 ztr loves math 【数学】
- hdoj 1025 Constructing Roads In JGShining's Kingdom 【LIS】
- 基础篇_包(package)
- HTML的本地数据库报错
- C#开发的进化史
- std::ref 有什么用
- PowerShell调用WMI
- redis安装
- 20145120 《Java程序设计》第9周学习总结
- Android Studio 2.+使用分享——关于未签名Apk第一次运行黑屏or白屏
- Python lambda表达式
- 2016年4月14日--4月30日(12小时,剩3009小时)
- nginx安装配置
- 一起talk C栗子吧(第一百四十一回:C语言实例--文件操作:基于文件指针一)
- 地理定位跟踪
- 常见的命令行操作
- C++ ofstream和ifstream详细用法
- Java-Write Once,Run Anywhere
- Bootstrap进度条组件知识详解