Introduction to the method of importing module module according to string in Python (with code)

不言
Release: 2019-03-06 13:48:31
forward
3102 people have browsed it

本篇文章给大家带来的内容是关于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;]
Copy after login

输出datetime_module即为module对象datetime。

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

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

The above is the detailed content of Introduction to the method of importing module module according to string in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!