码迷,mamicode.com
首页 > 编程语言 > 详细

python内置函数__import__

时间:2016-04-23 23:12:59      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:python   python内置函数   __import__   

我们知道import语句是用来导入外部模块的,当然还有from...import...也可以,但是其实import实际上是使用builtin函数__import__来工作的。 
    在一些程序中,我们可以动态地去调用函数,如果我们知道模块的名称(字符串)的时候,我们可以很方便的使用动态调用。 

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()

使用__import__函数获得特定函数 

def getfunctionbyname(module_name,function_name):  
    module = __import__(module_name)  
    return getattr(module,function_name)

还可以使用这个函数实现延迟化的模块导入 

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


本文出自 “陆雅亮” 博客,请务必保留此出处http://luyaliang.blog.51cto.com/3448477/1767085

python内置函数__import__

标签:python   python内置函数   __import__   

原文地址:http://luyaliang.blog.51cto.com/3448477/1767085

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!