首页 > 代码库 > 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