Think Python/Classes and functions

Time
As another example of a user-defined type, we'll define a class called Time that records the time of day. The class definition looks like this:

We can create a new Time object and assign attributes for hours, minutes, and seconds:

The state diagram for the Time object looks like this:



Exercise 1
Write a function called  that takes a Time object and prints it in the form.

Hint: the format sequence  prints an integer using at least two digits, including a leading zero if necessary.

Exercise 2
Write a boolean function called  that takes two Time objects,  and , and returns  if   follows chronologically and  otherwise.

Challenge: don't use an  statement.

Pure functions
In the next few sections, we’ll write two functions that add time values. 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.

Here is a simple prototype of : The function creates a new Time object, initializes its attributes, and returns a reference to the new object. This is called a pure function because it does not modify any of the objects passed to it as arguments and it has no effect, like displaying a value or getting user input, other than returning a value.

To test this function, I’ll create two Time objects: start contains the start time of a movie, like Monty Python and the Holy Grail, and duration contains the run time of the movie, which is one hour 35 minutes.

figures out when the movie will be done. The result, 10:80:00</TT> might not be what you were hoping for. The problem is that this function does not deal with cases where the number of seconds or minutes adds up to more than sixty. When that happens, we have to “carry” the extra seconds into the minute column or the extra minutes into the hour column.

Here’s an improved version: Although this function is correct, it is starting to get big. We will see a shorter alternative later.

Modifiers
Sometimes it is useful for a function to modify the objects it gets as parameters. In that case, the changes are visible to the caller. Functions that work this way are called modifiers.

<TT>increment</TT>, which adds a given number of seconds to a <TT>Time</TT> object, can be written naturally as a modifier. Here is a rough draft: The first line performs the basic operation; the remainder deals with the special cases we saw before.

Is this function correct? What happens if the parameter <TT>seconds</TT> is much greater than sixty?

In that case, it is not enough to carry once; we have to keep doing it until <TT>time.second</TT> is less than sixty. One solution is to replace the <TT>if</TT> statements with <TT>while</TT> statements. That would make the function correct, but not very efficient. <DIV CLASS="theorem">Exercise 3 Write a correct version of <TT>increment</TT> that doesn’t contain any loops.</DIV> Anything that can be done with modifiers can also be done with pure functions. In fact, some programming languages only allow pure functions. There is some evidence that programs that use pure functions are faster to develop and less error-prone than programs that use modifiers. But modifiers are convenient at times, and functional programs tend to be less efficient.

In general, I recommend that you write pure functions whenever it is reasonable and resort to modifiers only if there is a compelling advantage. This approach might be called a functional programming style.

Exercise 4  Write a “pure” version of <TT>increment</TT> that creates and returns a new Time object rather than modifying the parameter.

Prototyping versus planning
The development plan I am demonstrating is called “prototype and patch.” For each function, I wrote a prototype that performed the basic calculation and then tested it, patching errors along the way.

This approach can be effective, especially if you don’t yet have a deep understanding of the problem. But incremental corrections can generate code that is unnecessarily complicated—since it deals with many special cases—and unreliable—since it is hard to know if you have found all the errors.

An alternative is planned development, in which high-level insight into the problem can make the programming much easier. In this case, the insight is that a Time object is really a three-digit number in base 60 (see <TT>wikipedia.org/wiki/Sexagesimal</TT>)! The <TT>second</TT> attribute is the “ones column,” the <TT>minute</TT> attribute is the “sixties column,” and the <TT>hour</TT> attribute is the “thirty-six hundreds column.”

When we wrote  and <TT>increment</TT>, we were effectively doing addition in base 60, which is why we had to carry from one column to the next.

This observation suggests another approach to the whole problem—we can convert Time objects to integers and take advantage of the fact that the computer knows how to do integer arithmetic.

Here is a function that converts Times to integers: And here is the function that converts integers to Times (recall that <TT>divmod</TT> divides the first argument by the second and returns the quotient and remainder as a tuple).

You might have to think a bit, and run some tests, to convince yourself that these functions are correct. One way to test them is to check that  for many values of <TT>x</TT>. This is an example of a consistency check.

Once you are convinced they are correct, you can use them to rewrite : This version is shorter than the original, and easier to verify.

Exercise 5

Rewrite '<TT>increment</TT>' using   and .

In some ways, converting from base 60 to base 10 and back is harder than just dealing with times. Base conversion is more abstract; our intuition for dealing with time values is better.

But if we have the insight to treat times as base 60 numbers and make the investment of writing the conversion functions ( and ), we get a program that is shorter, easier to read and debug, and more reliable.

It is also easier to add features later. For example, imagine subtracting two Times to find the duration between them. The naïve approach would be to implement subtraction with borrowing. Using the conversion functions would be easier and more likely to be correct.

Ironically, sometimes making a problem harder (or more general) makes it easier (because there are fewer special cases and fewer opportunities for error).

Debugging
A Time object is well-formed if the values of <TT>minutes</TT> and <TT>seconds</TT> are between 0 and 60 (including 0 but not 60) and if <TT>hours</TT> is positive. <TT>hours</TT> and <TT>minutes</TT> should be integral values, but we might allow <TT>seconds</TT> to have a fraction part.

These kind of requirements are called invariants because they should always be true. To put it a different way, if they are not true, then something has gone wrong.

Writing code to check your invariants can help you detect errors and find their causes. For example, you might have a function like  that takes a Time object and returns <TT>False</TT> if it violates an invariant: Then at the beginning of each function you could check the arguments to make sure they are valid:

Or you could use an <TT>assert</TT> statement, which checks a given invariant and raises an exception if it fails:

<TT>assert</TT> statements are useful because they distinguish code that deals with normal conditions from code that checks for errors.

Glossary
<DL CLASS="description"><DT CLASS="dt-description">prototype and patch:</DT><DD CLASS="dd-description"> A development plan that involves writing a rough draft of a program, testing, and correcting errors as they are found. </DD><DT CLASS="dt-description">planned development:</DT><DD CLASS="dd-description"> A development plan that involves high-level insight into the problem and more planning than incremental development or prototype development. </DD><DT CLASS="dt-description">pure function:</DT><DD CLASS="dd-description"> A function that does not modify any of the objects it receives as arguments. Most pure functions are fruitful. </DD><DT CLASS="dt-description">modifier:</DT><DD CLASS="dd-description"> A function that changes one or more of the objects it receives as arguments. Most modifiers are fruitless. </DD><DT CLASS="dt-description">functional programming style:</DT><DD CLASS="dd-description"> A style of program design in which the majority of functions are pure. </DD><DT CLASS="dt-description">invariant:</DT><DD CLASS="dd-description"> A condition that should always be true during the execution of a program. </DD></DL>

Exercise 6
Write a function called  that takes a Time object and a number and returns a new Time object that contains the product of the original Time and the number. Then use   to write a function that takes a Time object that represents the finishing time in a race, and a number that represents the distance, and returns a Time object that represents the average pace (time per mile).

Exercise 7
Write a class definition for a Date object that has attributes <TT>day</TT> , <TT>month</TT> and <TT>year</TT> ''. Write a function called  that takes a Date object, <TT>date</TT> and an integer, <TT>n</TT> ,and returns a new Date object that represents the day <TT>n</TT> days after <TT>date</TT> . Hint: “Thirty days hath September...” Challenge: does your function deal with leap years correctly? See <TT>wikipedia.org/wiki/Leap_year</TT>''

Exercise 8
The <TT>datetime</TT> module provides <TT>date</TT> and <TT>time</TT> ''that are similar to the Date and Time objects in this chapter, but they provide a rich set of methods and operators. Read the documentation at <TT>docs.python.org/lib/datetime-date.html</TT> .''


 * Use the <TT>datetime</TT> module to write a program that gets the current date and prints the day of the week.
 * Write a program that takes a birthday as input and prints the user’s age and the number of days, hours, minutes and seconds until their next birthday.