默认数组参数意外不为空
可能的重复:
Python 中的“最不令人惊讶”:可变默认参数 < /p>
def stackdemo(stack=[]):
stack.append('q')
return stack
stackdemo()
print stackdemo()
返回['q','q']
,而
stackdemo([])
print stackdemo([])
使用相同的函数仅返回 ['q']
,如预期的那样。
如果使用默认值,为什么 Python 会重用数组?我错过了什么吗?
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
def stackdemo(stack=[]):
stack.append('q')
return stack
stackdemo()
print stackdemo()
returns ['q','q']
, whereas
stackdemo([])
print stackdemo([])
with the same function returns just ['q']
, as expected.
Why does Python appear to reuse the array if the default is used? Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
列表是一个可变对象。来自 doc:
默认值仅计算一次。当默认值是可变对象(例如列表、字典或大多数类的实例)时,这会有所不同。
使用
None
来实现:A list is a mutable object. From doc:
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.
Do it with
None
:在Python中,变量是通过对象引用传递的,而不是通过值传递的。
这意味着在这种情况下您正在修改
stack=[]
变量。如果您想避免这种行为,则必须在函数内生成变量,因为在这种情况下它将在运行时生成。
In Python variables are passed by object reference, not by value.
This means that in this case you are modifying the
stack=[]
variable.If you want to avoid this behaviour, than you have to generate the variable within the function since it will be generated on runtime in that case.