您的位置:首页 > 其它

一个简单的时间类的定制

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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: