python中根據字符串導入模塊module
需要導入importlib,使用其中的import_module方法
import importlib
modname = 'datetime'
datetime_module = importlib.import_module(modname)
print(datetime_module)
# <module 'datetime' from 'C:\\Users\\huchengyue\\AppData\\Local\\Programs\\Python\\Python37\\lib\\datetime.py'>
obj = getattr(datetime_module,'datetime')
print(obj.now())
# 2019-03-05 23:25:16.077121
print(dir(datetime_module))
# ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
輸出datetime_module即為module對象datetime
通過反射獲得其中的屬性或方法
調用dir函數查看其中地方屬性或方法