练习17-1
在一个时间类中实现 add_time()方法,能够打印出增加指定秒数后的时间。
1
2 class Time(object):
3 def print_time(self):
4 print '%.2d:%.2d:%.2d'%(self.hour,self.minute,self.second)
5 def time_to_int(self):
6 minutes = self.hour * 60 + self.minute
7 seconds = minutes * 60 +self.second
8 return seconds
9 def int_to_time(self,seconds):
10 time = Time()
11 minutes,time.second = divmod(seconds,60)
12 time.hour,time.minute = divmod(minutes,60)
13 return time
14 def add_time(self,seconds):
15 seconds += self.time_to_int()
16 return self.int_to_time(seconds)
17
18 start = Time()
19 start.hour = 10
20 start.minute = 0
21 start.second = 0
22 start.print_time()
23 end = start.add_time(3600)
24 end.print_time()
运行结果如下:
练习17-5
为Point类编写一个add方法,可以接收一个Ponit对象或者一个元组。
如果第二个操作对象是一个Point对象,则方法应该返回一个新的Point对象,其x坐标是两个操作对象的x坐标的和,y坐标也是类似。
如果第二个操作对象是一个元组,方法则将第一个元素和x坐标相加,将第二个坐标和y坐标相加,并返回一个包含相加结果的新的Point对象。
1 import types
2
3 class Point(object):
4 def __init__(self,x=0,y=0):
5 self.x = x
6 self.y = y
7
8 def __str__(self):
9 return "%.2d,%.2d"%(self.x,self.y)
10
11 def __add__(self,other):
12 if isinstance(other,Point):
13 point = Point()
14 point.x = self.x + other.x
15 point.y = self.y + other.y
16 return point
17 elif type(other) is types.TupleType:
18 point = Point()
19 point.x = self.x + other[0]
20 point.y = self.y + other[1]
21 return point
22
23 if __name__ =='__main__':
24 point1 = Point(10,20)
25 point2 = Point(30,40)
26 print point1+point2
27 point3 = Point(10,20)
28 point4 = (30,40)
29 print point3 + point4