retain values between fun calls
Kent Johnson
kent at kentsjohnson.com
Sun May 14 09:49:39 EDT 2006
George Sakkis wrote:
> 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? and how to make it so it does?
>>
>> thanks
>>
>> # it does
>> def f(a, L=[]):
>> L.append(a)
>> return L
>> print f('a')
>> print f('b')
>>
>>
>> # it does not
>> def f(a, b=1):
>> b = a + b
>> return b
>> print f(1)
>> print f(2)
>
> It's a FAQ:
> http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects.
>
> Whenever you want to control one or more objects beyond the lifetime of
> a single function call, your first thought should be to use a class to
> couple behaviour with state:
>
> class SomeFancyClassName(object):
> def __init__(self, b=1):
> self.b = b
> def f(self, a):
> self.b += a
> return self.b
>
> x = SomeFancyClassName()
> print x.f(1)
> print x.f(2)
If you make the class callable you can match the original syntax:
In [40]: class F(object):
....: b=1
....: def __call__(self, a):
....: F.b += a
....: return F.b
....:
....:
In [41]: f=F()
In [42]: f(1)
Out[42]: 2
In [43]: f(2)
Out[43]: 4
Alternately you can use an attribute of the function to save the state:
In [35]: def f(a):
....: f.b += a
....: return f.b
....:
In [36]: f.b=1
In [37]: f(1)
Out[37]: 2
In [38]: f(2)
Out[38]: 4
Kent
More information about the Python-list
mailing list