以编程方式确定函数所需的参数数量 - Python [英] Programmatically determining amount of parameters a function requires - Python

查看:32
本文介绍了以编程方式确定函数所需的参数数量 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的命令行实用程序,并使用字典作为一种 case 语句,其中关键字链接到其适当的功能.这些函数都需要不同数量的参数,所以目前要检查用户是否输入了每个函数所需的正确数量的参数,我将所需的数量以 {Keyword:(FunctionName, AmountofArguments) 形式放在字典 case 语句中}.

I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their appropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form {Keyword:(FunctionName, AmountofArguments)}.

这个当前的设置工作得非常好,但是我只是想知道是否有办法确定函数中所需的参数数量,我只是想知道是否有办法确定函数中所需的参数数量,而我的谷歌尝试到目前为止没有返回任何价值,但我知道如何args 和 kwargs 可能会搞砸这样的命令,因为它们允许的参数数量是无限的.

This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.

推荐答案

inspect.getargspec():

获取函数参数的名称和默认值.返回包含四项内容的元组:(args, varargs, varkw, defaults).args 是参数名称的列表(它可能包含嵌套列表).varargs 和 varkw 是 * 和 ** 参数或 None 的名称.defaults 是默认参数值的元组,如果没有默认参数,则为 None;如果此元组有 n 个元素,则它们对应于 args 中列出的最后 n 个元素.

Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

这篇关于以编程方式确定函数所需的参数数量 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆