Carrying variables over from function to function
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Sep 26 17:07:13 EDT 2005
Ivan Shevanski a écrit :
> 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? Heres a quick example of what I'm talking about.
>
> def abc():
> x = 1
> y = x + 1
> print y
>
> def abcd():
> y = x + 1
> print y
>
> abc()
> abcd()
>
> the output would be:
>
>>>> abc()
>
> 2
>
>>>> abcd()
>
> Traceback (most recent call last):
> File "(stdin)", line 1, in ?
> File "(stdin)", line 2, in abcd
> NameError: global name 'x' is not defined
>
>>>>
>
>
> See, I want y in the second function to equal 4, carrying the x from the
> first function over to the next. Is there any way to do this?
>
Actually, there are at least 3 ways to do it.
1/ Dirty solution:
------------------
x = 0
def abc():
global x
x = 1
print x + 1
def abcd():
global x
print x + 1
2/ functional solution:
-----------------------
def make_funcs():
x = 0
def _abc():
x = 1
return x + 1
def _abcd():
return x + 1
return _abc, _abcd
abc, abcd = make_funcs()
print abc()
print abcd()
3/ OO solution:
---------------
class Foo(object):
def __init__(self):
self._init_x()
def _init_x(self):
self._x = 1
def abc(self):
self._init_x()
return self.abcd()
def abcd(self):
return self._x + 1
f = Foo()
print f.abc()
print f.abcd()
Now guess which are:
A/ the pythonic solution
B/ the worst possible solution
C/ the most arcane solution
!-)
More information about the Python-list
mailing list