【问题标题】:python version of javascript's arguments object - does it exist?javascript 的 arguments 对象的 python 版本 - 它存在吗?
【发布时间】:2013-07-10 22:03:29
【问题描述】:

在 JavaScript 中,每个函数都有一个特殊的 arguments 预定义对象,其中包含有关传递给函数调用的参数的信息,例如

function test() {
  var args = Array.prototype.slice.call(arguments);
  console.log(args);
}

参数可以轻松转储到标准数组:

test()
// []

test(1,2,3)
// [1, 2, 3]

test("hello", 123, {}, [], function(){})
// ["hello", 123, Object, Array[0], function]

我知道在 Python 中我可以使用标准参数、位置参数和关键字参数(就像定义的 here)来管理动态参数号 - 但是 Python 中有没有类似于 arguments 对象的东西?

【问题讨论】:

  • 没有。就像你说的,最接近的是像*args**kwargs 这样的可变参数,但那些只会给你“额外”的论点,而不是所有的论点。在 Python 中对 arguments 的需求有所减少,因为(与 Javascript 不同)不可能使用错误数量的参数调用函数(即,如果一个函数需要两个参数,只用一个参数调用它会出错)。你想完成什么让你想使用arguments之类的东西?
  • @BrenBarn 我试图在 python 中实现所有的记忆技术(基于 javascript 模式)。在 JS 中,你大量使用 arguments,例如您可以使用一个参数(这是一个要记忆的函数)创建一个标准的memoize 函数,它将返回封闭的记忆函数。这是使用arguments 完成的,如您所见here(参见自动记忆一章)。
  • 不要试图复制 JavaScript 模式,而是四处寻找 Python 中的记忆示例。在 Python 中,您可以制作一个 memoize 装饰器,它可以与您描述的那种 JS 函数类似地使用。谷歌搜索“Python memoize”会给你很多想法。
  • 无论如何,在 Python 中没有像 arguments 这样的东西,正如我所见。谢谢。
  • 幸运的是,我找到了这个问题的副本:Get a list/tuple/dict of the arguments passed to a function?

标签: javascript python function arguments


【解决方案1】:

它在 python 中不存在,但你可以调用 locals() 作为函数中的第一件事,此时它应该只有参数

>>> def f(a,b):
...    args = locals()
...    for arg, value in args.items():
...        print arg, value
...    return a*b
...

【讨论】:

  • 确实如此,但如果函数有可变参数,您只会将它们作为元组/字典获取,而不是“扁平”与常规参数组合。
猜你喜欢
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多