python中根据字符串导入模块module的方法介绍(附代码)


本文摘自php中文网,作者不言,侵删。

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

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

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

1

2

3

4

5

6

7

8

9

10

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函数查看其中地方属性或方法。

以上就是python中根据字符串导入模块module的方法介绍(附代码)的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

深入类的属性介绍与使用

了解Python中的字符串是什么吗?

Python为什么是面向对象的

Python中的析构函数详解

Python之requests模块的使用方法详解

Python中argparse库的基本使用(示例)

Python中协程实现tcp连接的代码示例

Python是什么软件

Python学习笔记之open()函数打开文件路径报错问题

Python中可变对象和不可变对象详解

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...