[Tutor] Classes v2, thoughts/suggestions please

Alan Gauld alan.gauld at btinternet.com
Sat Jul 12 19:08:25 CEST 2008

"Paul Melvin" <paul at assured-networks.co.uk> wrote

>  i have come up with a working class for a square,

Well done. It might not be the most elegant solution on the
inside but it isn't too bad from the users point of view and thats
what you should aim for IMHO.

> I was thinking about using *args to get maybe the colour
> information in,

I would define polygon to take a list of points as a parameter
of init so you put the onus on the user to pass in  tbe points
in a list. That makes the init method easy:

Class Polygon:
    def __init__(self, pList, filled=True, line_width=1):
        self.points = pList
        self.filled = filled
        self.line_width = line_width

Your draw method is as before but instead of repeating
the code 4 times just put it into a loop that iterates over
the points list, something like:

def draw(self):
    if self.filled:
    for p in self.pList
        glColor4f(p.col[0], p.col[1], p.col[2], p.col[3])
        glVertex2i(int(p.x), int(p.y))
    if not filled and line_width != 1:  # reset to default

Note that I put it as the draw method not as a separate
function. There is little point in having a class then calling
a separate function to which you have to pass all the
data in the class!

> And how can i go about testing that i get appropriate values during 
> the
> testing/building phase (generally speaking), is it lots of 
> print/return
> statements and then remove them?

I'm not sure what you mean by "appropriate values" in this context.
Since you are drawing graphics I suspect you will have to just
draw them in a simple canvas and visually ensure the result is
what you expect?

You could try implementing a __str__ method in each class that
lets you print out a nicely formatted report of the Point and/or
Polygon data, which would allow you to do:

p = Point(.....)
print p
s = Polygon([p,p2,p3,p4])
print s

That would allow you to see what the graphic parameters will
be before drawing.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list