language/python
class 동적으로 import하기
아르르르를를르
2020. 8. 29. 16:31
class가 있는 module위치를 import 한 후 class_name으로 class를 호출한다.
import importlib
module = importlib.import_module(module_name)
class = getattr(module, class_name)
main.py
import importlib
def call_by_classname():
class_path = "callable.Callable"
path = class_path.split(".")
class_name = path[-1]
module_path = ".".join(path[:-1])
module = importlib.import_module(module_path)
call = getattr(module, class_name)().run()
call_by_classname()
callable.py
class Callable:
def __init__(self):
pass
def run(self):
print("hello")