1. 介绍
我们知道import语句是用来导入外部模块的,当然还有from...import...也可以,但是其实import实际上是使用builtin函数__import__来工作的。 在一些程序中,我们可以动态地去调用函数,如果我们知道模块的名称(字符串)的时候,我们可以很方便的使用动态调用。
2. 使用__import__函数获得特定函数
def getfunctionbyname(module_name,function_name):
module = __import__(module_name)
return getattr(module,function_name)
3. 实现延迟化的模块导入
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") # 这时候可以利用__init__方法延迟导入string模块
print string.lowercase
转载自:http://david-je.iteye.com/blog/1756788