Python中默认参数的规则是什么?
今天我遇到了一件我认为很奇怪的事情。
>>> import StringIO
>>> def test(thing=StringIO.StringIO()):
... thing.write("test")
... print thing.getvalue()
...
>>> test()
test
>>> test()
testtest
>>> test()
testtesttest
>>> test()
testtesttesttest
>>> test()
testtesttesttesttest
在今天之前,我会把这行读
def test(thing=StringIO.StringIO()):
为:
声明一个函数,其 kwargs 字典在调用时默认有一个新的
StringIO
作为键“thing”的值,并将其添加到当前范围。
但从这个例子来看,我认为它更像是:
声明一个函数。构造一个字典,其中包含一个新的
StringIO
。将其分配给函数的默认 kwargs 并将函数添加到当前作用域。
这是正确的解释吗?对于默认 kwargs 是否还有其他需要注意的问题?
I came across something today that I considered very odd.
>>> import StringIO
>>> def test(thing=StringIO.StringIO()):
... thing.write("test")
... print thing.getvalue()
...
>>> test()
test
>>> test()
testtest
>>> test()
testtesttest
>>> test()
testtesttesttest
>>> test()
testtesttesttesttest
Before today I would have read the line
def test(thing=StringIO.StringIO()):
as:
Declare a function which, whose kwargs dictionary, when called has a new
StringIO
by default as the value for the key 'thing', and add it to the current scope.
but from the example I think it's more like:
Declare a function. Construct a dictionary with a new
StringIO
in it. Assign this to the default kwargs of the function and add the function to the current scope.
Is this the correct interpretation? Are there any other gotchas to be aware of for default kwargs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的第二个定义是完全正确的。任何可变对象都会发生这种行为。常见的习惯用法是使用
None
作为防护。请参阅 Python 2.x 陷阱和地雷 上的答案更多细节。
Your second definition is perfectly correct. This behavior will happen with any mutable object. The common idiom is to use
None
as a guard.See this answer on Python 2.x gotcha's and landmines for more detail.
是的,第二种解释是正确的。这是 Python 中的陷阱之一。这里已经讨论过很多次了。例如,请参阅:“最少惊讶”和可变默认参数
Yes, the second interpretation is correct. It's one of the gotchas in Python. It's has been discussed here numerous times. See for example: "Least Astonishment" and the Mutable Default Argument