We know that the import statement is for importing external modules, and of course from...import ... Yes, but actually import actually works using the BUILTIN function __import__.
In some programs, we can dynamically call the function, if we know the name of the module (string), we can easily use dynamic invocation.
import glob,os modules = [] for module_file in glob.glob ("*-plugin.py"): try : module_name,ext = os.path.splitext ( Os.path.basename (module_file)) module = __ import__ (module_name) modules.append (module) except importerror: pass #ignore broken modules #say hello to all modules for module in modules: module.hello ()
Use the __import__ function to get a specific function
def getfunctionbyname (module_name,function_name): module = __import__ (module_name) return GetAttr (module,functio N_name)
You can also use this function to implement deferred module import
class lazyimport: def __init__ (Self,module_name): self.module_name = module_name self.module = none def __getattr__ (Self, Name): if self.module is None: self.module = __import__ (Self.module_name) return getattr (Self.module,name) string = lazyimport ("string") print string.lowercase
This article is from the "Lu Yaliang" blog, make sure to keep this source http://luyaliang.blog.51cto.com/3448477/1767085
Python built-in function __import__