[Tutor] quick OO pointer

Alan Gauld alan.gauld at freenet.co.uk
Mon Aug 7 14:12:22 CEST 2006


> now, i have a few functions in some scripts that i would like to 
> reuse
> across the board. But, they dont really fit the "object" thing, i 
> dont
> thing. Basically, i have a bunch of functions that do different 
> things and i
> would like one script to hold them all.

You can put normal functions in a module and reuse them sure.
If they operate on the same kinds of data then a class would be
more appropriate but otherwise functions are fine.

Its probably good to try to group them into families if possible.
And you definitely want to use Functional Programming principles
to maximise reuse. By that I mean:
1) No use of global variables
2) Pass everything in by parameters
3) Use default values to minimise the number of values the user sets
4) pass multiple values back in tuples where appropriate
5) make sure that the same set of input values always
    returns the same value - no hidden state

Consider a number of smaller modules with related functionns too.
Its tempting to just create a module called mystuff or similar that
holds everything, but you then wind up with every project
depending on mystuiff and small changes affect lots of code.
Better to have small modules with only a few functions that can
be imported as needed. Grouping the functions around the kind
of data they manipulate is a good start - but that brings us back
to objects again :-)


> def write_something_to_log(logfile, something)
>    f = open(logfile, 'a')
>    f.write('%s\n' % something)
>    f.close()
>    return 'success'
>
> and i wanted to use this same function in about four different 
> scripts, do i
> need a class ? Do i need to just create a script full of common 
> functions
> that i can access ? and if so, how ?

##############
# file: mylogger.py
def write_something_to_log(logfile, something)
    f = open(logfile, 'a')
    f.write('%s\n' % something)
    f.close()
    return 'success'
######################

#############
# file myprog.py
import mylogger

mylogger.write_something('logfile.txt', 'hello world')
##############

As simple as that!
Just make sure the module file is where it can be found by import...

More on creating modules in my tutorial topic on "Functions & 
Modules".

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