[Tutor] quick OO pointer

Jordan Greenberg jordangreenberg at gmail.com
Mon Aug 7 09:07:23 CEST 2006


shawn bright wrote:
> Hello there,
> 
> a while back i wrote a module called DbConnector.py that allowed me to run
> different types of SQL queries. Cool enough.
> i did it mostly to handle the open and close of a db connection so i
> wouldn't have to worry about 'too many connection' errors.
> it makes a connection, runs a query, then closes the connection.
> The reason i write this, is that i know how the module works to make a
> connection 'object'
> 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.
> do i need to define a class for this, or can you import a function from
> another script ?
> 
> like if i have
> 
> 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 ?
> usually in the tutorials i read, they deal with OO and classes. Most
> commonly a class called Person. Then person has different attributes. But
> these functions are just bits of code that i want to reuse
> what is the cleanest way to do something like this ?
> 
> thanks
> 
> sk

If your function write_something_to_log is in file myfunctions.py you
can just do:
from myfunctions import write_something_to_log

and then use write_something_to_log() just like it was defined in that file.

Example:
#file: test1.py
def spam():
	print "Spam, eggs, and toast"

#file: myscript.py
from test1 import spam
spam()
#prints "Spam, eggs, and toast"

Hope this helps!
-Jordan Greenberg



More information about the Tutor mailing list