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 1 year has passed since last update.

python でクラス名を文字列で指定してインスタンスを作成する

Posted at

やりたいこと

  • クラス名を文字列で指定して、指定したクラスのインスタンスを取得する

やったこと

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)

参考

0
0
1

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?