Mutable default arguments in Python
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have written the following python program:
#!/usr/bin/env python
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
print bug()
print bug()
The result i would expect is
[1]
[1]
But i got
[1]
[1, 1]
Is this a bug?
No, this is not a bug and this behaviour has been around in Python for a very long time.
The problem is that the list object is mutable, ie you can change it, and when you call a function you don't get a new default value. What's happening is this:
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
At this point the function bug
has been created and the list that is default value for numbers
created.
print bug()
Now we've called bug once and added 1
to the list that was created when the function was defined.
print bug()
When we call the function again we get the same list as before so we get two 1
s added to the list.
The usual solution is to define your function as follows:
def bug(numbers = None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers
Read this for more details.
numbers=[]
is evaluated only once (when the function is defined). So it's always the same list.
To avoid this, change the function like this:
def not_a_bug(numbers=None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers
链接地址: http://www.djcxy.com/p/28544.html
上一篇: Python中的可变默认方法参数
下一篇: Python中的可变默认参数