Python获取函数参数个数和默认参数

Python015

Python获取函数参数个数和默认参数,第1张

创建一个函数用来计算三个数的和,如下:

下来,我们对其进行调用:

假设我们要计算这个函数返回结果的平均值。那么此时,我们只需将和值除以参数个数即可,那么参数个数怎么获取呢?你可能会说:数一下就知道了。那么假设此时有很多的参数,你还去数吗?此时,明显这个方法是不恰当的,那么有没有更加方便、高效的方法呢?我们接着往下看。

通过上面这个例子,我们不但可以获取参数个数,还可以获取所有变量名以及默认返回值。此时,我们只需根据自己的需求,去应用就可以了,那么以上的问题,就自然解决了。

我这里用的是IDLE(我自己也觉得有点低端),Python3(2应该也可以)

>>>help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out

the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing

Python programs and using Python modules. To quit this help utility and

return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type

"modules", "keywords", "symbols", or "topics". Each module also comes

with a one-line summary of what it doesto list the modules whose name

or summary contain a given string such as "spam", type "modules spam".

help>sum

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)

Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.

This function is intended specifically for use with numeric values and may

reject non-numeric types.

解释一下:先在Shell输入help(),它就会问你你要哪个函数的说明。然后你输入对应函数(比如sum),就可以看到这一行:sum(iterable, start=0, /),也就是说你要先输入iterable参数,start可以选择输入(有默认值)。

或者还有一种方法:用的时候直接输入函数加上左括号 比如sum( 然后你就可以看到下面有一个框,然后按照说明写就好了。如果不小心不见了,就可以把左括号去掉再重新输入,就可以再看到这个框啦!