[模組管理篇] 如何動態載入模組(module)和類別(class) - tsungjung411/python-study GitHub Wiki

範例1

├── my_module.py
└── main.py

my_module.py

class SayHello:
    def __init__(self):
        print('SayHello.__init__()')

    def say(self):
        print('hello')

main.py

module = __import__('my_module')
print('module:', module, '\n')
print('dir(module):', dir(module), '\n')

klass = getattr(module, 'SayHello')
print('class:', klass)

執行結果: $ python main.py

module: <module 'my_module' from '/home/diatango_lin/tj_tsai/workspace/ml_scikit/my_module.py'> 

dir(module): ['SayHello', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] 

class: <class 'my_module.SayHello'> 

參考資料