我知道我可以使用*args来定义具有任意数量参数的函数。我的问题有点不同:如果我希望参数的数量由一个变量控制怎么办?例如,参数的数量应该是2n,其中n的值是在代码的早期计算的?
当将*args
与len
一起使用时,您可以获得参数的数量(因为args
是一个元组(,并根据该数量采取行动(包括一些测试用例(:
number = 2
def func(*args):
if len(args) != number * 2:
raise TypeError(f'Expected {number * 2} arguments, got {len(args)}')
# do some other stuff
# else clause not needed
# testing
test_cases = [
(1, 2, 3),
(1, 2, 3, 4),
(1, 2, 3, 4, 5)
]
for arguments in test_cases:
print(f'Calling function with {len(arguments)} arguments')
try:
func(*arguments)
except TypeError as e:
print(f'Raised an exception: {e}')
else:
print('Executed without exceptions')
print()
# output:
# Calling function with 3 arguments
# Raised an exception: Expected 4 arguments, got 3
#
# Calling function with 4 arguments
# Executed without exceptions
#
# Calling function with 5 arguments
# Raised an exception: Expected 4 arguments, got 5