簡體   English   中英

Python - 方法參數中的值解包順序

[英]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不能同時分配2310

請注意,雖然合法,但有些人不鼓勵在關鍵字 arguments 之后解壓縮可迭代的 arguments,如此所述,盡管語法最終被裁定保留。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM