やりたいこと
- クラス名を文字列で指定して、指定したクラスのインスタンスを取得する
やったこと
get_attr を使います。
Python3
# Python 3.9.13
# getattr_sample.py
import sys
class Hoge():
def __init__(self, output: str):
print(f"{output}")
cls = getattr(sys.modules[__name__], 'Hoge')
cls_a = cls('This is Hoge(a)')
実行結果
$ python getattr_sample.py
This is Hoge(a)