12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

154 Chapter 16. Classesand functions16.2 PurefunctionsIn the next few sections, we’ll write two functions that add time values. They demonstrate twokinds of functions: pure functions and modifiers. They also demonstrate a development plan I’llcall prototype and patch, which is a way of tackling a complex problem by starting with a simpleprototype and incrementally dealing withthe complications.Here isasimpleprototype ofadd_time:def add_time(t1, t2):sum = Time()sum.hour = t1.hour + t2.hoursum.minute = t1.minute + t2.minutesum.second = t1.second + t2.secondreturn sumThe function creates a new Time object, initializes its attributes, and returns a reference to the newobject. This is called a pure function because it does not modify any of the objects passed to it asarguments and it has no effect, like displaying a value or getting user input, other than returning avalue.To test this function, I’ll create two Time objects: start contains the start time of a movie, likeMonty <strong>Python</strong> and the Holy Grail, and duration contains the run time of the movie, which is onehour 35minutes.add_timefigures out when themovie willbe done.>>> start = Time()>>> start.hour = 9>>> start.minute = 45>>> start.second = 0>>> duration = Time()>>> duration.hour = 1>>> duration.minute = 35>>> duration.second = 0>>> done = add_time(start, duration)>>> print_time(done)10:80:00Theresult,10:80:00mightnotbewhatyouwerehopingfor. Theproblemisthatthisfunctiondoesnot deal with cases where the number of seconds or minutes adds up to more than sixty. When thathappens, we have to “carry” the extra seconds into the minute column or the extra minutes into thehour column.Here’s an improved version:def add_time(t1, t2):sum = Time()sum.hour = t1.hour + t2.hoursum.minute = t1.minute + t2.minutesum.second = t1.second + t2.second

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!