[Tutor] Re: Tutor digest, Vol 1 #1738 - 10 msgs

Jeff Shannon jeff@ccvcorp.com
Fri, 05 Jul 2002 10:55:39 -0700


Charlie Clark wrote:

> On 2002-07-04 at 19:55:02 [+0000], you wrote:
> > class Beeper(Tkinter.Tk):
> >   def __init__(self):
> >     Tkinter.Tk.__init__(self)
> >     Tkinter.Button(self, text=3D"Beep",
> >       command=3Dself.beep).pack()
> >     Tkinter.Button(self, text=3D"Quit",
> >       command=3Dself.quit).pack()
> >
> >   def beep(self):
> >     print "Beep"
> >
> > if __name__=3D=3D"__main__":
> >   b =3D Beeper()
> >   b.mainloop()
> >
> > Why has my Beeper instance no attribute 'beep' ??
>
> Well, I think there are two things wrong but the error message is a
> standard Python gotcha: you are calling beep() before you have assigned it.

Actually, no, the beep() method is *not* being called before assigning to it.
The attribute *should* be getting created during class-definition time.  When
the instance is being initialized (b = Beeper() calls Beeper.__init__() ), the
beep() method has already been defined.

My suspicion is that the original code, which threw the AttributeError,
probably suffered from an indentation problem.  If the 'def beep(self):' line
were not properly lined up, it would not be read as part of the Beeper class;
subsequently, any attempt to use Beeper.beep() would give exactly the
AttributeError shown.  There is no such error in the code as posted, though --
Nicole, did you copy & paste the code, or did you retype it?  If you retyped it
(or fiddled with the formatting for it, or replaced tabs with spaces, or...)
then that probably corrected the error -- do the same thing with your original
code, and you should be fine.  ;)


> But even if you define beep earlier I think you have a problem by calling a
> method as if it were an attribute.
> self.beep is an attribute
> beep(self) is a method and is directly accessible from within instances of
> the class even if the calls look the same from outside

self.beep is an attribute whose value is a (bound) method object -- what Nicole
is doing (command=self.beep) is the proper way to get a reference to a bound
method.  (A bound method is one that is already associated with a specific
instance of a class -- it already has the self parameter specified -- whereas
an unbound method is *not* associated with a class instance, and needs to have
an instance passed to it.)

Jeff Shannon
Technician/Programmer
Credit International