[Tutor] functions instead of classes

Daniel Ehrenberg littledanehren at yahoo.com
Wed Dec 17 21:59:41 EST 2003


I was trying to learn PyGTK, but I thought the style
of object orientation used was a bit odd because it
didn't need to be inherited from anything, most of the
code was in __init__, and only one function, main()
was ever run externally. I rewrote it to be a function
that locally contains some functions. This is what
wxLua uses to construct its GUIs, roughly, and it
makes for much shorter code. Here's a simple
application that makes a window appear that has a
button with Hello world on it, and when you click it,
it writes Hello world to the console.

import gtk

def HelloWorld():
    def hello(widget, data=None):
        print "Hello World"

    def destroy(widget, data=None):
        gtk.main_quit()

    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.connect("delete_event", destroy)
    window.connect("destroy", destroy)
    window.set_border_width(10)
    button = gtk.Button("Hello World")
    button.connect("clicked", hello, None)
    window.add(button)
    button.show()
    window.show()
    gtk.main()

if __name__ == "__main__":
    HelloWorld()

This is around 5 lines shorter than when using
objects, and with objects you have to always use those
annoying prefixes. Is there anything wrong with this
coding style? I've heard that object orientation makes
it more reusable, but when are you going to reuse a
GUI layout? It's in a function so it can already be
called more than once.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/



More information about the Tutor mailing list