标签:style blog http color io ar sp div 2014
In the next few sections, we’ll write two versions of a function called add_time, which calculates the sum of two Time objects. They demonstrate two kinds of functions: pure functions and modifiers. They also demonstrate a development plan I’ll call prototype and patch, which is a way of tackling a complex problem by starting with a simple prototype and incrementally dealing with the complications.
class Time:
""" represents the time of day
attributes: hour, minute, second"""
def print_time(self):
print(‘%d:%d:%d‘ % (self.hour,self.minute,self.second))
def after(self,t):
if(self.hour < t.hour):
return False
elif(self.hour == t.hour):
if(self.minute < t.minute):
return False
elif(self.minute == t.minute):
if(self.second <= t.second):
return False
else: return True
return True
def add_time(t1,t2):
total = Time()
total.hour = t1.hour + t2.hour
total.minute = t1.minute + t2.minute
total.second = t1.second + t2.second
if(total.second >=60):
total.second -= 60
total.minute +=1
if(total.minute >=60):
total.minute -=60
total.hour +=1
return total
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 36
time2 = Time()
time2.hour = 11
time2.minute = 58
time2.second = 55
Although this function is correct, it is starting to get big. We will see a shorter alternative later.
from Thinking in Python
标签:style blog http color io ar sp div 2014
原文地址:http://www.cnblogs.com/ryansunyu/p/4003924.html