Introductory Programming
Fall 2004

Homework 12

The reading for this assignment is Chapter 14 of How to think....

Date methods

  1. Start with your solution to Homework 11 or download mine at

    http://wb/ip/code/ip_hw11_soln.py
    

  2. Using Evaluations 8 and 9 as a template, convert the Date class so that it uses methods rather than functions. This is a little tricky to do incrementally, because when you change the definition of a function you also have to change the places where it is invoked. Here are some suggestions on how to make and test small changes:

    1. Move make_date inside the Date class and change the name to __init__.

      HINT: In emacs, there is a command in the Python menu called Shift region right. If you select a block of code and then invoke this command, it indents the entire block correctly.

      Don't forget that inside an __init__, you get self as a parameter, so you don't have to create it yourself, and you don't have to return anything.

      Now change the places where make_date is invoked so that they instantiate Date objects.

    2. Move print_date inside the Date class and change the name to __str__. Change the name of the parameter to self and make the method fruitful; that is, it should return a string representation of the date and print nothing.

      Now change the place where print_date is invoked so it uses a print statement.

    3. By now you should be getting the idea, so I will skip the detailed instructions: just make days_since_2000 a method.

  3. That's it! Changing a function to a method is mostly a matter of syntax; it doesn't really change what the program does. The primary benefit of writing methods is that they organize the program by associating data objects with the operations they can perform. In a small program like this, that benefit is probably not apparent, but as programs get bigger, this kind of organization is a useful tool for managing complexity.