参数中间的*args属性。

问题描述 投票:0回答:1

我正在研究在python函数之间使用*args的效果,但我不明白这个用例是否实用,甚至是否可能,它在我的IDE上被标记为错误。

def my_function(a, *args, b):
print(a)
print(args)
print(b)


my_function(1, 2, 3, 4, 5)

我的输出结果如下。

Traceback (most recent call last):
  File "C:/Users/axel_/PycharmProjects/Python_Subject_Exam/3_new_exam_args_in_middle.py", line 10, in <module>
    my_function(1, 2, 3, 4, 5)
TypeError: my_function() missing 1 required keyword-only argument: 'b'

所以,*args必须放在任何函数参数的最后,放在中间是无效的python代码,对吗?

我也测试了一下,按原定计划放在最后。

def my_function(a, b, *args):
    print(a)
    print(args)
    print(b)


my_function(1, 2, 3, 4, 5)

输出

1
(3, 4, 5)
2

Process finished with exit code 0
python args
1个回答
0
投票

这个模式是用来强制用户指定所有参数后的 *args在你的情况下,你 必须 设置 b. 这将被接受。

my_function(1, 2, 3, 4, 5, b=6)
© www.soinside.com 2019 - 2024. All rights reserved.