0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【python3】関数のキーワード引数を動的に指定して呼び出す

Last updated at Posted at 2020-12-15

0. 結論

f(arg1,arg2)に対しては次のようにするとよい
f(**{"arg1":hoge, "arg2":fuga})

1. やりたいこと

関数fがあり、fの仮引数はarg1およびarg2だとする。
どちらか一方のみを指定して呼ぶ場合、f(arg1="hoge")とかf(arg2="fuga")のように呼ぶことが出来る。

このときarg1を指定するか、それともarg2を指定して呼ぶかを動的に決定したい。

2. やり方

例えば「arg1を呼ぶかarg2を呼ぶかを確率的に決めたい場合」は次のようにできる。

python
import numpy as np
確率的に決まる引数 = lambda: "arg1" if np.random.rand()> 0.5 else "arg2"

def f(arg1="(empty)", arg2="(empty)"):
    print("arg1 = "+str(arg1)+"\narg2 = "+str(arg2))

f(**{確率的に決まる引数():"fuga"})
# 半分の確率で
#
# arg1 = fuga
# arg2 = (empty)
#
# と表示され,もう半分の確率で
#
# arg1 = (empty)
# arg2 = fuga
#
# と表示される
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?