Python 动态导入 __import__
程序员文章站
2022-09-26 17:48:35
import sys,tarcebackimport_str = "django.db.modle.Q"#将会导入Qimport_calss(import_str)#导入类库def import_class(import_str): mod_str, _sep, class_str = import... ......
import sys,tarceback
import_str = "django.db.modle.Q"
#将会导入Q
import_calss(import_str)
#导入类库
def import_class(import_str): mod_str, _sep, class_str = import_str.rpartition('.') __import__(mod_str) try: return getattr(sys.modules[mod_str],class_str) except AttributeError: raise ImportError('Class %s cannot be found (%s)' % (class_str, traceback.format_exception(*sys.exc_info())))
#实例化 def import_object(import_str, *args, **kwargs): return import_class(import_str)(*args, **kwargs)