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