首页 > 代码库 > Pure functions
Pure functions
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 Truedef 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 totaltime = Time()time.hour = 11time.minute = 59time.second = 30time1 = Time()time1.hour = 11time1.minute = 59time1.second = 36time2 = Time()time2.hour = 11time2.minute = 58time2.second = 55
Although this function is correct, it is starting to get big. We will see a shorter alternative later.
from Thinking in Python
Pure functions
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。