retain values between fun calls
bruno at modulix
onurb at xiludom.gro
Mon May 15 04:31:00 EDT 2006
Gary Wessle wrote:
> Hi
>
> the second argument in the functions below suppose to retain its value
> between function calls, the first does, the second does not and I
> would like to know why it doesn't?
Fisrt thing to remember is that function's default args are eval'd only
once - when the def block is eval'd, which is usually at import time.
> # it does
> def f(a, L=[]):
> L.append(a)
Here, you are modifying the (list) object bound to local name L.
> return L
> print f('a')
> print f('b')
>
>
> # it does not
> def f(a, b=1):
> b = a + b
And here, you are *rebinding* the local name b to another object.
Understand that modifying an object in-place and rebinding a name are
two really different operations...
> return b
> print f(1)
> print f(2)
> and how to make it so it does?
The Q&D solution is to wrap :
def f(a, b = [1])
b[0] = b[0] + a
return b[0]
But this is really a hack - it's ok for a throw-away script, but may not
be the best thing to do in a more serious piece of software.
The clean solution to maintain state between calls is to use a custom
class - hopefully, Python is OO enough to let you write your own callables:
class MyFunc(object):
def __init__(self, initstate=1):
self._state = default
def __call__(self, a):
self._state += a
return self._state
f = MyFunc(1)
print f(1)
print f(2)
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list