Inner classes

Samuele Pedroni pedroni at inf.ethz.ch
Fri Jun 15 14:59:13 EDT 2001


I hope you know that you can do the following in jython:

class StupidExample:

 def butAAction(self,e):
   ....

 def butBAction(sel,e):
   ...

 def __init__(self):
   self.butA = JButton("A",actionPerformed=self.butAAction);
   self.butB = JButton("B",actionPerformed=self.butBAction);

or even lambdas instead of bounded methods if your code is short enough

<wink> Samuele Pedroni.


Glen Starchman wrote:

> Paul Prescod wrote:
> > In Java all of the code would have to be in a class and _onclick would
> > have to be defined in *another* class (because you can't pass references
> > to functions/methods). Thus you need inner classes.
>
> One of the most difficult (well, maybe not *difficult*, but
> definitely time-consuming) things in converting Java classes to
> Jython (or Python) classes is that bastard of all Java features: the
> anonymous inner class. Given code that looks like:
>
> class StupidExample
> {
>     StupidExample()
>     {
>         JButton button = new JButton("Dumb Button");
>         button.addActionListener(new ActionListener()
>                                  {
>                                       actionPerformed(event e)
>                                       {
>                                            doSomething();
>                                            ...
>                                       }
>                                   }
>     }
> }
>
> What happens if you decide to add another button that has similar
> functionality? In this case, you end up writing yet another
> anonymous inner class. Icky.
>
> So, in Jython, what I do is either implement ActionListener in the
> parent class, and write a multi-purpose handler, or write a second
> class for the handler:
>
> class StupidExample(ActionListener):
>     def __init__(self):
>         self.button = JButton("Dumb Button")
>         self.button.addActionListener(self)
>
>     def actionPerformed(e):
>         if e.getSource==self.button:
>             doSomething()
>             ...
>
> Now, after typing all of that I have forgotten my point... oh,
> yeah... Inner Classes (and *especially* Anonymous Inner Classes)
> suck.
>
> >
> > In some languages without first-class classes, you hack classes through
> > function "closures". In languages without first-class functions, you
> > hack functions through "one-method classes". Python has both and you
> > don't have to hack!
>
> Hurray for Python!
>
> > --
> > Take a recipe. Leave a recipe.
> > Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list