首頁  >  文章  >  後端開發  >  python中根據字串導入模組module的方法介紹(附程式碼)

python中根據字串導入模組module的方法介紹(附程式碼)

不言
不言轉載
2019-03-06 13:48:313134瀏覽

本篇文章给大家带来的内容是关于python中根据字符串导入模块module的方法介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

python中根据字符串导入模块module

需要导入importlib,使用其中的import_module方法

import importlib
modname = 'datetime'
datetime_module = importlib.import_module(modname)
print(datetime_module)
# <module &#39;datetime&#39; from &#39;C:\\Users\\huchengyue\\AppData\\Local\\Programs\\Python\\Python37\\lib\\datetime.py&#39;>
obj = getattr(datetime_module,&#39;datetime&#39;)
print(obj.now())
# 2019-03-05 23:25:16.077121
print(dir(datetime_module))
# [&#39;MAXYEAR&#39;, &#39;MINYEAR&#39;, &#39;__builtins__&#39;, &#39;__cached__&#39;, &#39;__doc__&#39;, &#39;__file__&#39;, &#39;__loader__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;__spec__&#39;, &#39;date&#39;, &#39;datetime&#39;, &#39;datetime_CAPI&#39;, &#39;time&#39;, &#39;timedelta&#39;, &#39;timezone&#39;, &#39;tzinfo&#39;]

输出datetime_module即为module对象datetime。

通过反射获得其中的属性或方法。

调用dir函数查看其中地方属性或方法。

以上是python中根據字串導入模組module的方法介紹(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除