Python 関数の引数いろいろ
基本のキすぎて人目につく箇所に書くのが憚られるのでここに書く。
参考書籍: www.oreilly.co.jp
引数のデフォルト値
def f(food, animal="dogs"): print(f"I like {food} and {animal}.") >>> f("puddings", "cats") I like puddings and cats. >>>f("puddings") I like puddings and dogs.
キーワード引数
def f(food, animal="dogs"): print(f"I like {food} and {animal}.") >>>f(food="tomatos", animal="humstars") I like tomatos and humstars. >>>f("tomatos", animal="humstars") I like tomatos and humstars.
- 呼び出し時にキーを指定
- 複数の引数がある場合、必ず位置引数が先でキーワード引数があと。
引数の個数が可変の引数
def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind, ".") for arg in arguments: print(arg) print("-" * 40) print(keywords) keys = sorted(keywords.keys()) for kw in keys: print(kw, ":", keywords[kw]) >>> cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", Client="Jhon Cleese", sketch="Cheese shop Sketch") -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger . It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- Client : Jhon Cleese shopkeeper : Michael Palin sketch : Cheese shop Sketch
*引数名
は仮引数に対応しないすべての位置指定型引数が入ったタプル**引数名
は仮引数に対応しないキーを持つすべてのキーワード引数が入った辞書
アンパック代入
- タプルやリストの要素を展開(アンパック)して複数の変数に代入できる
# 前提:タプルのパックとは >>> t = 1, 2, 3 >>> t (1, 2, 3) # 前提:タプルのアンパックとは >>> a, b, c = t >>> a 1 >>> b 2 >>> c 3
>>> list(range(2,5)) [2, 3, 4] # ↑の式をタプルのアンパックで作ってみる # 関数を呼ぶ際引数名の前に*をつけることでアンパックした引数を渡すことができる >>> args=[2,5] >>> list(range(*args)) [2, 3, 4] # * つけなかったら勿論ダメ >>> list(range(args)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'list' object cannot be interpreted as an integer
# **引数名、とすることで辞書型をキーワード型にアンパック可能 def f(food, animal="dogs"): print(f"I like {food} and {animal}.") d = {"food": "apple", "animal": "rabbits"} >>f(**d) I like apple and rabbits.