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

发布于 2024-08-30 19:03:19 字数 302 浏览 12 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

行雁书 2024-09-06 19:03:19

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

更好的方法如下:

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

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:

class Test:
    def test(self, p, d = None):
        if d is None:
            d = {}
        d.update(p)
        return d
書生途 2024-09-06 19:03:19

Python 中的默认参数是定义函数时设置的任何对象,即使您设置了可变对象。这个问题应该解释这意味着什么以及为什么Python是SO问题 least python 中的惊人之处:可变的默认参数

基本上,每次调用函数时都会使用相同的默认对象,而不是每次都创建新的副本。例如:

>>> def f(xs=[]):
...   xs.append(5)
...   print xs
... 
>>> f()
[5]
>>> f()
[5, 5]

解决此问题的最简单方法是将实际默认参数设为 None,然后只需检查 None 并在函数中提供默认值,例如:

>>> def f(xs=None):
...   if xs is None:
...     xs = []
...   xs.append(5)
...   print xs
... 
>>> f()
[5]
>>> f()
[5]

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:

>>> def f(xs=[]):
...   xs.append(5)
...   print xs
... 
>>> f()
[5]
>>> f()
[5, 5]

The easiest way around this is to make your actual default argument None, and then simply check for None and provide a default in the function, for example:

>>> def f(xs=None):
...   if xs is None:
...     xs = []
...   xs.append(5)
...   print xs
... 
>>> f()
[5]
>>> f()
[5]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文