Recently I've been doing things like this:
import Tkinter
class C(object):
def __init__(self):
self.root = Tkinter.Tk()
def f():
print 'hello'
self.button = Tkinter.Button(master=self.root, command=f, text='say hello')
as opposed to something like this:
import Tkinter
class C(object):
def __init__(self):
self.root = Tkinter.Tk()
self.button = Tkinter.Button(master=self.root, command=self.f, text='say hello')
def f(self):
print 'hello'
The question isn't specific to Tkinter, but it's a good example. The function f
is only used as the callback for the button, so I've chosen to define it inside __init__
. That way, only code inside __init__
even knows about f
's existence - outer scopes don't start getting cluttered up with names, and the user doesn't need to care about a load of methods designed to be internal.
My question is: is this regarded as good style? I'm worrying because I've got a GUI class with quite a lot of buttons - __init__
is starting to look very long, with a lot of local function definitions. Is there a more appropriate alternative that I should be using?
f
is doing more than justprint 'hello'
. It won't fit inside a lambda function. – Lierne