Requirements: In recent time based on the Django framework, the development of various business layer monitoring code, each business monitoring logic is different, so need to develop monitoring sub-modules, dynamic import calls.
Project Name: Demo_django
App:common_base, Monitor_master
Monitoring sub-module: demo_django/common_base/modules/classname.py
#-*-Coding:utf-8-*-class ClassName (object):d EF mod1 (self):p rint "Mod1" def mod2 (self):p rint "Mod2"
Note: The module name is the same as the class name
dynamic application module: Demo_ django/common_base/module_partiton.py
def test (): clsname = "ClassName" method = "Mod1" Importmodule = Lazyimport ("monitor_base.modules." + Clsname, Clsname) # import classname Module is_true = hasattr (Importmodule, clsname) # Check if classname class is in classname module if is_true: classname = GetAttr (Importmodule, clsname) obj = classname (self.hostlist, Self.way) # instantiates classname class MTD = GetAttr (obj , method) MTD () # calls the Mod1 method class Lazyimport (object): "" " Dynamic Import Module" " def __init__ (self, module_ Name, Module_class): "" " :p Aram module_name: :p Aram Module_class: : return: equivalent to form module_name Import Module_class "" " self.module_name = module_name self.module_class = Module_class Self.module = None def __getattr__ (self, name): if Self.module is none: self.module = __import__ ( Self.module_name, Fromlist=[self.module_class]) return getattr (self.module, name) if __name__ = = ' __main__ ': Test ()
Reference: http://www.cnblogs.com/bluefrog/archive/2012/05/11/2496439.html
Python Dynamic call module, class, Method (Django project)