Day 9

Today

Reading Journal Debrief

“In about one sentence using your own words, what is a class?”


There was some confusion about all the string formatting operations (e.g. %.2d) in the reading, so this might be a good time to revisit the day 4 notes on string formatting. You can also check out Think Python 14.3


“Write a function called mul_time 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.”

Some disagreement: Is mul_time a pure function or a modifier?

Follow-up: why does this matter?

Exercise: more geometry

In this exercise, you will define methods for Line and Rect geometry classes. These classes have a slightly different interface than the ones you worked on in your reading journal - we’ll think about the impact of those differences as we work.

Download geometry.py, and complete it so that the doctests pass.

Note: two of the methods in this file, Line.intersection and Rect.intersection, have their doc tests commented out. (Yes, they’re commented out within a docstring.) You don’t need to implement these - they’re the subject of a Going Beyond exercise below.

Think about:

If you have extra time, you can extend your work in any of the following directions. Any of these can be done independently of the others.

Going beyond: refactoring

It seems like these classes were written by someone who hadn’t heard of your Point class. Rewrite them to take your Point as an argument.

This can be fairly tricky, since:

Going beyond: geometry algorithms

Un-comment the test cases in Line.intersection and Rect.intersection and make them pass.

Think about what Line.intersection and Rect.intersection should do when the two lines or rectangles don’t intersect. Can you think of several answers? – what are their pro and cons?

Going beyond: graphics

Visualize your geometry by employing turtles to draw it for you. Write a function called draw_rect that takes a Turtle object and a Rect and uses the Turtle to draw the Rectangle.

To go way beyond, you could start drawing your shapes using pygame.

Going beyond: more shapes

Add a Circle class that takes a center point and a radius. Implement the various geometry methods from your other classes (e.g. area). Exercise 1 from Think Python chapter 15 may be helpful for framing your ideas.

Going beyond: test case design

Think about the mistakes a non-malicious programmer could make while implementing these methods. Do the test cases detect these mistakes? What would you add?

You may do this exercise by drawing lines, squares, and points on a piece of paper, instead of covering coordinates to numbers.