[英]Python - value unpacking order in method parameters
def fun(a, b, c, d):
print('a:', a, 'b:', b, 'c:', c, 'd:', d)
為什么這個有效
fun(3, 7, d=10, *(23,))
並打印出:
a: 3 b: 7 c: 23 d: 10
而這
fun(3, 7, c=10, *(23,))
才不是
Traceback (most recent call last):
File "/home/lookash/PycharmProjects/PythonLearning/learning.py", line 10, in <module>
fun(3, 7, c=10, *(23,))
TypeError: fun() got multiple values for argument 'c'
With *(23,)
, you are unpacking the values in the tuple (23,)
as positional arguments, following the positional arguments that are already defined, namely 3
for a
and 7
for b
, so 23
would be assigned to parameter c
,這就是為什么fun(3, 7, d=10, *(23,))
有效,但是在fun(3, 7, c=10, *(23,))
中,您還將值10
分配給c
作為關鍵字參數,因此它被認為是沖突,因為c
不能同時分配23
和10
。
請注意,雖然合法,但有些人不鼓勵在關鍵字 arguments 之后解壓縮可迭代的 arguments,如此處所述,盡管語法最終被裁定保留。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.