[Tutor] Placing entire Application inside a class

Kent Johnson kent37 at tds.net
Wed Dec 19 13:26:03 CET 2007


Jim Morcombe wrote:
> I have just read through "Creating a GUI in Python - by Dakota Lemaster"
>  
> In it, Dakota recomends placing the entire application within a class.
>  
> Why is this so?  Surely in many cases you end up with a constructor for 
> the class that is cumbersome and complex?

Many GUI frameworks (though not Tkinter) include an application class 
that you must instantiate and to start the application's event loop. It 
is convenient to subclass the framework's application class for your own 
initialization.

Event callbacks for button presses, etc, generally must access some 
shared state, either the app's data model or other GUI elements or both. 
Shared state requires either global variables or a class instance to 
hold the state. Here again, an app class is useful.

In my experience most apps don't have that many constructor arguments. 
If there are many options, usually some kind of settings object is 
created and used by the app.

> Is this a recomended Python programming technique?

For GUI programs it works well. For non-GUI programs classes may not be 
needed at all, it depends on the requirements of the program. One of the 
strengths of Python is that it allows different programming styles, you 
can pick the one that fits the problem and your preferences.

> http://student-iat.ubalt.edu/sde/students/lemaster/COSC330/Final/sec4_AppClass.html

In TicTacToe.py, notice that the event handler labelClicked() accesses 
self.labelList and self.gameOver. This is an example of shared state.

The reset button is bound to a nested function; I think this would be 
better written as another method of the class also.

Kent


More information about the Tutor mailing list