[Tutor] Re: Tutor digest, Vol 1 #1738 - 10 msgs
Charlie Clark
charlie@begeistert.org
Thu, 04 Jul 2002 22:34:43 +0000
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.
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
a = Beeper()
a.beep
a.beep()
I'm not an expert on these things so I don't know what the real
consequences of this are but look at the following:
>>> class Charlie:
... def __init_(self):
... self.beep = "BeeeP"
... def beep(self):
... print "Beep!"
>>> a = Charlie
>>> a.beep
<unbound method Charlie.beep>
>>> a.beep()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method beep() must be called with instance as first
argument
Common sense says your naming convention is likely to cause confusion.
Charlie