首页 > 其他 > 详细

Pure functions

时间:2014-10-02 11:13:52      阅读:268      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣

Although this function is correct, it is starting to get big. We will see a shorter alternative later.

 

from Thinking in Python

Pure functions

原文:http://www.cnblogs.com/ryansunyu/p/4003924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!