Skip to content

Instantly share code, notes, and snippets.

@suganoo
Last active October 15, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suganoo/d21f46042779169d37aeefbab1da7fae to your computer and use it in GitHub Desktop.
Save suganoo/d21f46042779169d37aeefbab1da7fae to your computer and use it in GitHub Desktop.
【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