[英]Explain Keyword-Only Arguments (VarArgs) in Python
請看下面的代碼:-
#!/usr/bin/python
# Filename: total.py
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
有人可以解釋一下 *numbers 和 **keywords 是如何獲取參數的嗎? 非常感謝一個簡單的解釋提前致謝
在你的代碼numbers
分配的(1,2,3)的元組。 keywords
被分配一個字典,包含vegetables
和fruits
。
一顆星 ( *
) 定義位置參數。 這意味着您可以接收任意數量的參數。 您可以將傳遞的參數視為元組。
兩顆星 ( **
) 定義關鍵字參數。
參考資料可在此處獲得。
Python 2.x(在僅關鍵字參數之前)
def foo(x, y, foo=None, *args): print [x, y, foo, args]
foo(1, 2, 3, 4) --> [1, 2, 3, (4, )] # foo == 4
foo(1, 2, 3, 4, foo=True) --> TypeError
Python 3.x(帶有僅關鍵字參數)
def foo(x, y, *args, foo=None): print([x, y, foo, args])
foo(1, 2, 3, 4) --> [1, 2, None, (3, 4)] # foo is None
foo(1, 2, 3, 4, foo=True) --> [1, 2, True, (3, 4)]
def combo(x=None, *args, y=None): ... # 2.x and 3.x styles in one function
盡管經驗豐富的程序員理解 2.x 中發生的事情,但這是違反直覺的(只要有足夠的位置參數,位置參數就會綁定到foo=
而不管關鍵字參數如何)
Python 3.x 在PEP-3102 中引入了更直觀的僅關鍵字參數(varargs 后的關鍵字參數只能通過名稱綁定)
讓我們先分解函數。
這個總函數需要三個參數。
==========================================
計數 = 初始
*我們知道 initial 是一個包含值 5 的關鍵字參數。所以現在將值 5 分配給一個名為 count 的變量。
對於數字中的數字:
*數字是數字的占位符變量。
*我們知道 numbers 是一個任意參數,因此它可以采用任意數量的參數或值。
*所以現在數字將包含在執行函數時在 numbers 參數中傳遞的參數。
計數 += 數量
*每次循環遍歷數字參數並將計數添加到數字並返回計數
*當 count 為 5 時,它會遍歷參數並添加參數的第一個實例。 這將重復直到循環耗盡。
對於關鍵字的關鍵:
*這很棘手,因為這次參數是字典類型,其中包含鍵和該鍵的對應值。
計數 += 關鍵字[鍵]
返回計數
100 + 50 + (10, 1, 2, 3) => 166。
我知道這個答案太大了,但是理解每個函數的基本概念是一個全面的程序員的核心優勢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.