日々精進

新しく学んだことを書き留めていきます

pythonでメソッドの実引数に**を付けるとdictを展開してくれる

これ知らなかった。。コードを見た方がわかりやすいと思う。例は以下。

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)

参考:

docs.python.org