如何在Python函数中找到参数的数量?
在本文中,我们将了解如何计算Python中函数的参数数量。我们将使用在Python的函数定义中使用的称为 *args 的特殊语法。语法 *args 允许我们将可变数量的参数传递给函数。我们将在 *args 中使用 len()函数或方法来计算Python中函数的参数数量。
示例 1:
Python3
def no_of_argu(*args):
# using len() method in args to count
return(len(args))
a = 1
b = 3
# arguments passed
n = no_of_argu(1, 2, 4, a)
# result printed
print(" The number of arguments are: ", n)
Python3
def no_of_argu(*args):
# using len() method in args to count
return(len(args))
print(no_of_argu(2, 5, 4))
print(no_of_argu(4, 5, 6, 5, 4, 4))
print(no_of_argu(3, 2, 32, 4, 4, 52, 1))
print(no_of_argu(1))
输出 :
The number of arguments passed are: 4
示例 2:
Python3
def no_of_argu(*args):
# using len() method in args to count
return(len(args))
print(no_of_argu(2, 5, 4))
print(no_of_argu(4, 5, 6, 5, 4, 4))
print(no_of_argu(3, 2, 32, 4, 4, 52, 1))
print(no_of_argu(1))
输出 :
3
6
7
1