dict.update 会影响函数的 argspec 吗?
import inspect
class Test:
def test(self, p, d={}):
d.update(p)
return d
print inspect.getargspec(getattr(Test, 'test'))[3]
print Test().test({'1':True})
print inspect.getargspec(getattr(Test, 'test'))[3]
我希望 Test.test 的 argspec 不会改变,但由于 dict.update 它会改变。为什么?
import inspect
class Test:
def test(self, p, d={}):
d.update(p)
return d
print inspect.getargspec(getattr(Test, 'test'))[3]
print Test().test({'1':True})
print inspect.getargspec(getattr(Test, 'test'))[3]
I would expect the argspec for Test.test not to change but because of dict.update it does. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为字典是可变对象。当您调用 d.update(p) 时,您实际上是在改变字典的默认实例。这是一个常见的问题;特别是,您永远不应该使用可变对象作为参数列表中的默认值。
更好的方法如下:
Because dicts are mutable objects. When you call
d.update(p)
, you are actually mutating the default instance of the dict. This is a common catch; in particular, you should never use a mutable object as a default value in the list of arguments.A better way to do this is as follows:
Python 中的默认参数是定义函数时设置的任何对象,即使您设置了可变对象。这个问题应该解释这意味着什么以及为什么Python是SO问题 least python 中的惊人之处:可变的默认参数。
基本上,每次调用函数时都会使用相同的默认对象,而不是每次都创建新的副本。例如:
解决此问题的最简单方法是将实际默认参数设为
None
,然后只需检查None
并在函数中提供默认值,例如:A default argument in Python is whatever object was set when the function was defined, even if you set a mutable object. This question should explain what that means and why Python is the SO question least astonishment in python: the mutable default argument.
Basically, the same default object is used every time the function is called, rather than a new copy being made each time. For example:
The easiest way around this is to make your actual default argument
None
, and then simply check forNone
and provide a default in the function, for example: