3

The following is an except from a tutorial.


The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

This will print

[1]
[1, 2]
[1, 2, 3]

However, when I try this with a scalar variable:

>>> def acu(n, a = 0):
    "Test if local variables in functions have static duration"
    a = a + n
    return a


>>> acu (5)
5
>>> acu (5)
5

So why is this difference between the lifetimes of L and a?

4

1 回答 1

3

There is no difference. In the second part you are rebinding the local name a, not mutating the object it points to.

于 2013-05-23T09:47:13.243 回答