Carrying variables over from function to function

Roy Smith roy at panix.com
Sun Sep 25 19:49:13 EDT 2005


"Ivan Shevanski" <darkpaladin79 at hotmail.com> wrote:
> Alright heres my problem. . .Say I want to carry over a variable from one 
> function to another or even another run of the same function. Is that 
> possible?

You want one of two things.

The most obvious would be a global variable.  Something like this:

def abc():
    global x
    x = 1
    y = x + 1
    print y

def abcd():
    global x
    y = x + 1
    print y

This works, and is sometimes even the right thing to do, but in general, 
good software design looks for ways to decouple functions from each other 
and generally frowns on the use of global variables.

More likely, what you really want to do is declare a class, and have your 
shared variable be an instance variable.  Your two functions abc() and 
abcd() would then be methods of that class.



More information about the Python-list mailing list