モジュールのレッスン (3/4)
*args と **kwargs
変数数値を受け入れる関数が必要な場合があります。
引数。 Python には 2 つのツールがあります: *args (位置引数を収集します)
タプルに) および **kwargs (キーワード引数を辞書に集めます)。
*args: 変数の位置引数
def somma_tutto(*nums):
totale = 0
for n in nums:
totale += n
return totale
somma_tutto(1, 2, 3) # 6
somma_tutto(1, 2, 3, 4, 5) # 15
somma_tutto() # 0関数内の nums は、すべての値が渡された タプル です。の
名前は単なる慣例です。*args が最も一般的ですが、*nums または
*valori は完全に有効です。
**kwargs: 可変キーワード引数
def crea_config(**opzioni):
return opzioni
crea_config(debug=True, port=8080)
# {'debug': True, 'port': 8080}関数内では、opzioni は {param_name: value} を含む dict です。
すべてを組み合わせる
固定順序は次のとおりです: **通常パラメータ、*args、デフォルト パラメータ、**kwargs**。
def f(primo, *args, opzione="x", **kwargs):
print(primo, args, opzione, kwargs)
f(1, 2, 3, opzione="y", extra=10)
# 1 (2, 3) y {'extra': 10}呼び出しでの解凍: * および **
同じ演算子が逆に機能します。リスト/タプルを「展開」します。 位置引数に変換するか、辞書をキーワード引数に変換します。
def punto(x, y, z):
return (x, y, z)
coords = [1, 2, 3]
punto(*coords) # punto(1, 2, 3) → (1, 2, 3)
opts = {"x": 1, "y": 2, "z": 3}
punto(**opts) # punto(x=1, y=2, z=3)ラッパーパターン
def log_chiamata(fn, *args, **kwargs):
print(f"chiamo {fn.__name__} con {args=} {kwargs=}")
return fn(*args, **kwargs)
log_chiamata(max, 3, 1, 2) # calls max(3, 1, 2)
log_chiamata(sorted, [3, 1, 2], reverse=True)関数シグネチャでのパラメータの順序付け
複数の引数の型を受け入れる関数を定義する場合は、シグネチャ内の厳密な順序に従う必要があります。
- 標準の位置パラメータ。
- 位置可変引数
*args。 - デフォルト値を含むキーワードパラメータ。
- キーワード可変引数
**kwargs。
試してみてください
算術平均 (合計 / カウント) を返す `average(*nums)` を定義します。 10、20、30 で呼び出し、結果を `m` に代入します。 「m」を評価します。
ヒントを表示
sum(数値) / len(数値)
3 回の試行後に解決策が利用可能になります
復習演習
関数 `def point(x, y, z): return x + y + z` と dict `coords = {'x': 1, 'y': 2, 'z': 3}` を指定すると、ポイント アンパック coords を呼び出し、結果を `s` に代入します。 「s」を評価します。
ヒントを表示
ポイント(**座標)
3 回の試行後に解決策が利用可能になります
追加の課題
Write a function `multiply_all(*args)` that returns the product of all numbers passed as arguments. If no arguments are passed, it should return `1`. Finally, evaluate the call `multiply_all(2, 3, 4)`.
ヒントを表示
for ループを使用して、args 内の要素を反復処理し、その積を蓄積します。
3 回の試行後に解決策が利用可能になります