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

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

问题描述

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

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.

推荐答案

检查.getargspec()
$ b

inspect.getargspec():


获取函数参数的名称和默认值。返回四个元组的元组:(args,varargs,varkw,默认值)。 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天全站免登陆