定义 Python 参数数量由变量控制的函数

Defining Python Function with Number of Arguments Controlled by Variable

我知道我可以使用 *args 来定义具有任意数量参数的函数。我的问题有点不同:如果我希望参数的数量由变量控制怎么办?比如参数的个数应该是2n,其中n的值在代码前面是计算出来的?

您可以在将 *argslen 一起使用时获取参数的数量(因为 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