The purpose is to implement the module that should be applied when switching from the configuration file to run. It is complicated to use C # because it is a static language, so to switch dynamically, we only need to use reflection. python is much easier, as long asCodeBefore dynamic import, you can achieve the goal.
Assume that there is a package named "mypackage", which contains three modules: md01.py, md02.py, and md03.py, which implement the same method.
Def getstr (): Return "from md01/ 2/3"
Among them, 123 vary with Moudle.
So how can we use it?
From XML. Dom import minidomif _ name __= = "_ main _": # assume that an xml configuration file reads the Moudle node xml = ''' <? XML version = "1.0"?> <Root> <Moudle> md03 </Moudle> </root> ''' P = minidom. parsestring (XML) mdname = P. getelementsbytagname ("Moudle") [0]. firstchild. data mymod =__ import _ ("mypackage. "+ mdname, fromlist = [" * "]) # fromlist is very important to print mymod. getstr ()
During the test, the only thing that is ignored is the fromlist parameter in _ import _. No module can be obtained and only the package can be obtained, the reason is that the names of modules that may participate in the import must be written in fromlist,
This is a very good design. If you have a huge package, but you only need a few modules to participate, you can write the several modules into it.
If the imported module is in your own package, the fromlist is empty or you can send this parameter.