“46029˙CH12˙Miller” 2008/7/29 13:15 page 402 #10
402 CHAPTER 12 Your Father Was a Rectangle
The final method of our Canvas class is the draw method, which is simple to implement
but exposes one of the most powerful and important parts of object-oriented programming.
Notice that draw accepts a geometric object gObject as a parameter. After putting the
turtle into a state with its tail up, and tracing off, the only thing the draw method does is
call the _draw method on the gObject, passing our turtle as a parameter! It is important
to realize that the draw method belongs to the Canvas, while the _draw method belongs
to the GeometricObject. Although _draw may look strange to you, it is a perfectly legal
name for a function. We use _draw in this case to differentiate it from the draw method,
and to prevent programmers from inadvertently calling the draw method directly on a
GeometricObject.
If you think about it for a while, you may realize that the formal parameter of the draw
method can be any GeometricObject. This means that the Canvas does not know whether
it has to draw a Point,aLine, or any other Shape. We can solve this problem by using
the following code:
if isinstance(gObject,Point):
# code to draw a point
elif isinstance(gObject,Line):
# code to draw a line
elif isinstance(gObject,Circle):
# code to draw a circle
...
else:
print ('unknown geometric object')
While using isinstance to check the type of gObject would certainly work, object-oriented
programming provides us with polymorphism—a much more powerful way to handle
exactly this kind of problem that allows us to write a _draw method for each of our specific
geometric objects. Python is smart enough to call the right method, depending on the
type of object that is referenced by the gObject variable. As you will soon see, we will
implement a _draw method for the classes Point, Line, and GeometricObject. After we
have implemented these methods, we discuss the underlying mechanism that Python uses
to implement polymorphism.
12.4.2 GeometricObject
Let’s continue our implementation by writing the GeometricObject class. GeometricObject
and Canvas are peers at the top level of our inheritance hierarchy. The most important

Get Python Programming in Context now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.