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

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!