Python で動的にモジュール内のクラスを指定する
Python 3.5.2 で getattr を使って、モジュールから文字列でクラスを指定し、インスタンスを生成する。
ファイル構成は以下の通り
temp ├── main.py └── agents ├── __init__.py ├── agent1.py └── agent2.py
各ファイルの中身
# main.py import agents def run(agent_name): agent_class = getattr(agents, agent_name) agent = agent_class() agent.hello() if __name__ == '__main__': run('Agent1') run('Agent2')
# __init__.py from .agent1 import Agent1 from .agent2 import Agent2
#agent1.py class Agent1(object): def hello(self): print("Hello! I'm Agent1.")
# agent2.py class Agent2(object): def hello(self): print("Hello! I'm Agent2.")
これを実行すると
$ python main.py Hello! I'm Agent1. Hello! I'm Agent2.
参考文献