Instantly share code, notes, and snippets.

Embed
What would you like to do?
【globals()】文字列からクラス生成する
# ファイルが下記のように配置されてるとする
include_script_1.py
include_script_2.py
test_1.py
test_2.py
class TestInclude1:
def __init__(self):
print("TestInclude 1")
def call(self):
print("call TestInclude 1")
class TestInclude2:
def __init__(self):
print("TestInclude 2")
def call(self):
print("call TestInclude 2")
from include_script_1 import TestInclude1
from include_script_2 import TestInclude2
a = 6
b = 4
class Test:
def __init__(self):
print("Test class")
Test_cls_ogj = Test()
print(globals())
# 実行結果
Test class
{'a': 6, 'b': 4, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test_1.py', '__package__': None, 'Test_cls_ogj': <__main__.Test instance at 0x1006ef200>, 'TestInclude1': <class include_script_1.TestInclude1 at 0x1006b6668>, 'TestInclude2': <class include_script_2.TestInclude2 at 0x1006b6600>, 'Test': <class __main__.Test at 0x1006b6598>, '__name__': '__main__', '__doc__': None}
# ↑見にくいのでjsonの形式を整えます。
{
'a': 6,
'b': 4,
'__builtins__': <module '__builtin__' (built-in)>,
'__file__': 'test_1.py', '__package__': None,
'Test_cls_ogj': <__main__.Test instance at 0x1006ef200>,
'TestInclude1': <class include_script_1.TestInclude1 at 0x1006b6668>, #<---インポートしたクラス
'TestInclude2': <class include_script_2.TestInclude2 at 0x1006b6600>,       #<---インポートしたクラス
'Test': <class __main__.Test at 0x1006b6598>,
'__name__': '__main__',
'__doc__': None
}
from include_script_1 import TestInclude1
from include_script_2 import TestInclude2
class_name = "TestInclude1"
cls = globals()[class_name]
cls_obj = cls()
cls_obj.call()
print("----")
class_name = "TestInclude2"
cls = globals()[class_name]
cls_obj = cls()
cls_obj.call()
TestInclude 1
call TestInclude 1
----
TestInclude 2
call TestInclude 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment