[Tutor] passing arguments via an instance of a class

Alan Gauld alan.gauld at btinternet.com
Wed Apr 4 10:02:02 CEST 2007


"Che M" <pine508 at hotmail.com> wrote

> My problem is I don't understand how to create
> the class such that it a) expects to be passed two lists,

You've done that correctly by creating an init that takes xpoints
and ypoints and storing those as members of self.

> b) hands those lists off to its draw() method to use in
> drawing the graph.

You don't need to 'hand them off' to draw because draw
is part of self, therefore it can access self.xpoints and
self.ypoints directly.

>    def __init__(self,parent, xpoints=[], ypoints=[], id = -1,
>                     color = None, dpi = None,
>                     style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
>          wx.Panel.__init__(self, parent, id = id, style = style, 
> **kwargs)

I don't think you need to specify id and style since kwargs will
do that for you. But it shouldn't do any harm, its just extra work.

>        self.figure = Figure(None, dpi)
>        self.xpoints = xpoints
>        self.ypoints = ypoints

This is where you store the lists of points.

>    def draw(self):
>#if the following two lines were not commented out, the graph works 
>fine
>        #x = [1,2,3]
>        #y = [5,10,15]

you could do:

x = self.xpoints
y = self.ypoints

Or just wait and use seld.xpoints etc at the point of use.

>#this next just plots a red line using whatever x,y points given
>        self.subplot.plot(x,y, '-r')

So this could just be

self.subplot.plot(self.xpoints,self.ypoints,'-r')


#This is now the button which is supposed to feed the PlotPanel
#the points it needs.  It is a method of the wxFrame (code not shown)
>
>def OnButton1Button(self, event):
>#these are the points I want to be plotted when I push this button
>        xpoints=[2,4,6]
>        ypoints=[10,20,30]
>        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)

But this needs to use self to access the member values:

        self.weightplot = 
PlotPanel(self.notebook1,self.xpoints,self.ypoints)

> As is, when I press that button I get this error:
>
> Name Error:  global name xpoints is not defined.

Are you sure you get that error with the code you've posted?
It looks like the error I'd expect before yopu created the 2
hard coded lists above?

> Suggesting the draw() method never got passed the
> xpoints (or the ypoints) via the button press.

It doesn't, it should access them directly via self.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list