Adding an interface to existing classes

Spencer Pearson speeze.pearson at gmail.com
Sat Dec 24 18:49:59 EST 2011


On Dec 23, 9:13 am, Terry Reedy <tjre... at udel.edu> wrote:
> On 12/22/2011 3:21 AM, Spencer Pearson wrote:
>
> > I'm writing a geometry package, with Points and Lines and Circles and
> > so on, and eventually I want to be able to draw these things on the
> > screen. I have two options so far for how to accomplish this, but
> > neither of them sits quite right with me, and I'd like the opinion of
> > comp.lang.python's wizened elders.
>
> > Option 1. Subclassing.
> > The most Pythonic way would seem to be writing subclasses for the
> > things I want to display, adding a ".draw(...)" method to each one,
> > like this:
> > Option 2. A "draw" function, with a function dictionary.
>
> Option 3? Add a draw method to existing classes, rather than subclassing?
>
> --
> Terry Jan Reedy

Thanks for the response! Do you mean something like this?
class Point(GeometricObject):
    def intersect(self, other):
        ...
    def union(self, other):
        ...
    def draw(self, ...):
        ...

I'd like to avoid this, because... well, what I want is a geometry
package, and it seems to me that whistles and bells like GUI support
ought to be confined to subpackages. I'd look at this and think, "the
rest of the Point class deals with fundamental geometric reality.
What's this GUI method doing mixed in with my beautiful mathematical
purity?" Is this the wrong attitude to take?

Or did you mean this?
In file "geometry/gui.py":
def draw_point(point, ...):
    ...
Point.draw = draw_point

I've never modified an existing class before, and I fear the
unfamiliar. If that's what you meant... it's really an acceptable
thing to do? It seems like somebody might see "some_point.draw(...)"
and be confused by the method's absence in the Point class definition.

(A hybrid approach would be to say "draw = geometry.gui.draw_point"
inside the body of the Point class, setting the attribute there
instead of in gui.py, but that makes me uneasy for the same reason as
putting the function's full definition in the class.)

Thanks again,
-Spencer



More information about the Python-list mailing list