获取python函数中的参数数量

时间:2017-10-13 06:15:17

标签: python function testing

我创建函数,在函数中获取params的数量,但是只有在给出它时才给出数字,但是我真正需要的是通过获取func名来获取数字。

def a(a, b, c):
    par = len(locals())
    return par

z = a()

我需要将z等于3,但它会出错。

def a(a, b, c):
    par = len(locals())
    return par

z = a(1, 2, 3)

我需要机会在没有给予参数的情况下获得len。

1 个答案:

答案 0 :(得分:3)

Python允许您的函数使用arbitrary number of positional arguments

接受argument unpacking
def a(*args):  # allows any number of arguments without runtime errors
    par = len(args)  # args is a tuple of all the provided arguments
    return par

a(1, 2, 3)
# 3
a()
# 0