Mutable Default Arguments
Seemingly the most common surprise new Python programmers encounter is Python’s
treatment of mutable default arguments in function definitions.
What You Wrote
What You Might Have Expected to Happen
A new list is created each time the function is called if a second argument isn’t
provided, so that the output is:
[12]
[42]
What Does Happen
[12]
[12, 42]
A new list is created once when the function is defined, and the same list is used in each successive call.
Python’s default arguments are evaluated once when the function is defined, not
each time the function is called (like it is in say, Ruby). This means that if
you use a mutable default argument and mutate it, you will and have mutated that
object for all future calls to the function as well.
近期评论