Default method arguments

Peter Otten __peter__ at web.de
Fri Nov 18 04:54:48 EST 2005


Martin Miller wrote:

> Well, perhaps the same in the sense of name binding, but there's a
> subtle difference in replacing the 's = [n]'  with 'foo.s = n'.  Namely
> that in the former case (with the essay's original code) a separate
> container is created when foo() is first called and is what is used in
> subsequent calls to the function returned.  Whereas in the latter case
> where the foo object itself is used as the container, there's only a
> single container used by all returned objects -- which would cause
> problems if you try accumulating two or more different totals
> simultaneously.

[snip example using the outer foo() as a container]

You can easily get a unique container using the function attribute style, to
-- just use the inner function bar():

>>> def foo(n):
...     def bar(i):
...             bar.i += 1
...             re
...
>>>
>>> def foo(n):
...     def bar(i):
...             bar.s += i
...             return bar.s
...     bar.s = n
...     return bar
...
>>> a1 = foo(0)
>>> a2 = foo(0)
>>> a1(0), a2(0)
(0, 0)
>>> a1(1), a2(1)
(1, 1)

Peter




More information about the Python-list mailing list