[Tutor] is it legal to have a class within a def
jfabiani at yolo.com
Thu Jan 3 07:28:49 CET 2008
On Wednesday 02 January 2008 09:31:19 pm you wrote:
> johnf wrote:
> > def someMethod():
> > class MyClass(object):
> > .....
> > if something:
> > .....
> > return someval
> Legal? Well the police won't come after you!
That's a good thing!
> Python allows a class statement anywhere. So this use is part of the
> So the question becomes "why would you want to do that?"
> 1 - this usage creates a local object MyClass. The object will not be
> visible outside the function. The class definition is executed each time
> the function is called.
> 2 - the object could be returned or assigned to a global or added to a
> parameter that is a collection.
> 3 - if no instances are created in the function the object will
> disappear once the function execution ends.
1 and 3 are my reasons. I'm creating a Dabo app. When I attempted to create
a special class that contained a dialog box I discovered that the dialog
class created an indepentant type of window and allowed my program to
continue running without waiting for the dialog to return a value first.
However, I noticed if I created the dialog within a function my program
stopped and waited until the dialog was closed to continue. I think that I
could define the Classes outside of the function and just import them when
needed. But then I wanted a self contained function so I asked why not place
the class code in the function? What is the difference?
More information about the Tutor