[Tutor] is it legal to have a class within a def

Alan Gauld alan.gauld at btinternet.com
Thu Jan 3 19:13:18 CET 2008


"johnf" <jfabiani at yolo.com> wrote

> ....  If the user types in a partial of the key then the dialog
> appears and the user picks from the list.  The details of the dialog 
> are
> dynamic for each call (based on some meta data) of the showModal().

This might be a valid case for defining the class in the function 
since
it could be that the number of fields, the labels etc change depending
on the input values. That is exactly the kind of place where a local 
class
makes sense.

> I am very interested in this possible difference between importing 
> the class
> vs using the inline class.  Any thoughts as what the difference is 
> will help
> me understand Python a little better.

There is no great secret, its just that by putting the class 
definition
into the function you have to execute the definition each time you
execute the function. If you put the class in a module and import
it then the class definition is executed at import time and thats it.

But if you need to change the definition each time you instantiate the
dialog you will have a very complex init method so you might find
it easier to redefine the class each time instead.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list