python - 获取python函数的参数顺序?

标签 python reflection

我有以下功能:

def foo(a, b, c):
    print "Hello"

假设我知道它存在,并且我知道它需要三个名为 a、b 和 c 的参数,但我不知道顺序是什么。

我希望能够在给定字典的情况下调用 foo:

args = { "a": 1, "b" : 17, "c": 23 }

有没有办法找出参数传递的顺序?

最佳答案

你不需要;让 Python 为您解决这个问题:

foo(**args)

这会将您的字典用作关键字参数,这是完全合法的。当您使用关键字参数时,您可以按任何顺序使用 foo() 的参数:

>>> def foo(a, b, c):
...     print a, b, c
... 
>>> foo(c=3, a=5, b=42)
5 42 3
>>> args = {'a': 1, 'b' : 17, 'c': 23}
>>> foo(**args)
1 17 23

您仍然可以使用 inspect.getargspec() function 找出确切的顺序:

>>> import inspect
>>> inspect.getargspec(foo)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)

但为什么要养条狗并且自己吠叫呢?

关于python - 获取python函数的参数顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113443/

相关文章:

java - Android:使用 Java 反射更改私有(private)静态最终字段

python - 在 Python 中使用参数调用对象的方法

python - 如何对经纬度数据点进行聚类

python - datetime => timestamp 的差异仅在某些情况下?

python - 我可以像在 hgrc 文件中配置一些扩展一样配置 mercurial hooks 吗?

python - 生成随机数列表,总和为 1

python - 在Scrapy中,无法提取其中包含 "@"的链接文本

java - 将对象与原始类型进行比较

.net - 如何检测哪种 .NET 语言正在调用我的代码

go - 递归结构反射错误 : panic: reflect: Field of non-struct type