任意の引数

開発者向け中級 Python

Jasmin Ludolf

Curriculum Manager

定義済み引数の制限

def average(values):
    """Find the mean in a sequence of values and round to two decimal places."""

    average_value = sum(values) / len(values)
    rounded_average = round(average_value, 2)
    return rounded_average

# Using six arguments print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
開発者向け中級 Python

任意の位置引数

  • Docstring:カスタム関数の使い方を明確にするのに便利

  • 任意引数により、関数は任意の数の引数を受け取ることができる

# Allow any number of positional, non-keyword arguments
def average(*args):
    # Function code remains the same
  • 従来の命名法:*args

  • さまざまな用途に対応しながら、期待どおりの結果を生み出す!

開発者向け中級 Python

任意の位置引数を使用する

# Calling average with six positional arguments
print(average(15, 29, 4, 13, 11, 8))
13.33
開発者向け中級 Python

Argsによる単一のイテラブルの作成

  • *: Convert arguments to a single iterable (tuple)
# Calculating across multiple lists
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
開発者向け中級 Python

任意のキーワード引数

# Use arbitrary keyword arguments
def average(**kwargs):

average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
  • 任意のキーワード引数:**kwargs

  • keyword=value

開発者向け中級 Python

任意のキーワード引数を使用する

# Calling average with six kwargs
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# Calling average with one kwarg
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
  • ディクショナリ内の各key-valueペアは、キーワード引数と値にマッピングされる!
開発者向け中級 Python

Kwargsによる単一のイテラブルの作成

# Calling average with three kwargs
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
開発者向け中級 Python

練習しましょう!

開発者向け中級 Python

Preparing Video For Download...