1. 程式人生 > >Python 動態載入模組

Python 動態載入模組

lib資料夾下有test.py檔案:

test.py檔案內容如下:

class simple(object):
    def __init__(self):
        self.name='剛田武'

 在‘動態載入模組.py’檔案下動態載入test.py模組的方法如下:

module=__import__('lib.test')  #此時module相當於lib
print(module)
obj=module.test.simple()  #例項化,此時obj相當於lib.test.simple物件
print(obj.name)

 輸出為:

<module 'lib' (namespace)>
剛田武

 


 

官方推薦用法如下:

import importlib
test=importlib.import_module('lib.test')  #此時test相當於test.py檔案
print(test)
print(test.simple().name)

 輸出:

<module 'lib.test' from 'C:\\Users\\HJJ\\PycharmProjects\\python_learning\\Week8\\lib\\test.py
'> 剛田武