0
3

More than 3 years have passed since last update.

【@デコレータ使用篇】Pythonの関数を辞書(dict)のValueに格納して、Keyに応じた関数を呼出す

Last updated at Posted at 2020-11-27

前回記事「Pythonの関数を辞書(dict)のValueに格納して、Keyに応じた関数呼出しをする方法」の続編です。

( 参考にした書籍 )

(書籍)Julien Danjou(著)『Python ハッカーガイドブック』pp.142-143所収のサンプルコードを拡張しました。

iPython(Python3.9.0)
functions_dict = {}

def register(f):
    global functions_dict
    functions_dict[f.__name__] = f
    return f 

@register
def sample_func1():
    return 'bar'

print(functions_dict['sample_func1'])
# 実行結果
<function sample_func1 at 0x1085bf940>

print(functions_dict['sample_func1']())
# 実行結果
bar

@register
def sample_func2():
    return 'foo'

print(functions_dict)
# 実行結果
{'sample_func1': <function sample_func1 at 0x1085bf940>, 'sample_func2': <function sample_func2 at 0x10843b550>}

print(functions_dict['sample_func2']())
# 実行結果
foo

( 参考 )関数オブジェクト.nameで関数名をstr型で取り出すことができる

iPython(Python3.9.0)
def sample_func1():
    return 'bar'

関数名.nameで、関数の名称をstr型オブジェクトとして取得できる。

iPython(Python3.9.0)
print(sample_func1.__name__)
# 実行結果
sample_func1

print(type(sample_func1.__name__))
# 実行結果
<class 'str'>


以下はエラー

辞書オブジェクト[Key名]はエラー。
辞書オブジェクト['Key名']はOK。Keyはstr型オブジェクトを渡す必要があります。

iPython(Python3.9.0)
print(type(sample_func1.__name__))
# 実行結果
<class 'str'>

print(functions_dict[sample_func1])
# 実行結果
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-63-32923bc8e62e> in <module>
----> 1 print(functions_dict[sample_func1])

KeyError: <function sample_func1 at 0x1085bf940>

In [64]: print(functions_dict[sample_func1]())
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-64-af09e15405cf> in <module>
----> 1 print(functions_dict[sample_func1]())

KeyError: <function sample_func1 at 0x1085bf940>
0
3
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
3