gpt4 book ai didi

python - dict.update 会影响函数的 argspec 吗?

转载 作者:太空狗 更新时间:2023-10-30 02:23:40 26 4
gpt4 key购买 nike

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 它会改变。为什么?

最佳答案

因为字典是可变对象。当您调用 d.update(p) 时,您实际上是在改变 dict 的默认实例。这是一个常见问题;特别是,您应该永远不要使用可变对象作为参数列表中的默认值。

更好的方法如下:

class Test:
def test(self, p, d = None):
if d is None:
d = {}
d.update(p)
return d

关于python - dict.update 会影响函数的 argspec 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2730107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com