[Tutor] Python function seem to have a memory ???
by Simon Vandemoortele other posts by this author
Aug 11 2001 3:42PM messages near this date
[Tutor] OOP book
|
Re: [Tutor] Python function seem to have a memory ???
I am making my first contact with python through the means of the tutorial
(http://www.python.org/doc/current/tut/) and I would like some clarification
on the example:
--- quote ---
Important warning: The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list or dictionary.
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]
--- end quote ---
One thing I find astonishing about this is the fact that python functions
seem to have memory; each call of f() leads to a different result ! Does this
mean that the variable 'l' keeps its content even after the function returns
? This seems very strange to me as I have never seen it in other languages.
Some explanation/comments/corrections ?
Thx, Simon
--
If you took all the students that felt asleep in class and laid them
end to end, they'd be a lot more comfortable.
-- "Graffiti in the Big Ten"
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Simon Vandemoortele
dman
Danny Yoo
Kalle Svensson
Danny Yoo
Lloyd Kvam
|