python中根據字符串導入模塊module


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函數查看其中地方屬性或方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM