zoukankan      html  css  js  c++  java
  • Python 的内置函数__import__

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

    Python代码  收藏代码
    1. import glob,os  
    2.   
    3. modules = []  
    4. for module_file in glob.glob("*-plugin.py"):  
    5.     try:  
    6.        module_name,ext = os.path.splitext(os.path.basename(module_file))  
    7.        module = __import__(module_name)  
    8.        modules.append(module)  
    9.     except ImportError:  
    10.        pass #ignore broken modules  
    11.     #say hello to all modules  
    12.     for module in modules:  
    13.        module.hello()  



    使用__import__函数获得特定函数 

    Python代码  收藏代码
    1. def getfunctionbyname(module_name,function_name):  
    2.     module = __import__(module_name)  
    3.     return getattr(module,function_name)  



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

    Python代码  收藏代码
      1. class LazyImport:  
      2.       def __init__(self,module_name):  
      3.           self.module_name = module_name  
      4.           self.module = None  
      5.       def __getattr__(self,name):  
      6.           if self.module is None:  
      7.              self.module = __import__(self.module_name)  
      8.           return getattr(self.module,name)  
      9. string = LazyImport("string")  
      10. print string.lowercase  
  • 相关阅读:
    Node.js 笔记03
    Node.js 笔记02
    Node.js 笔记01
    源代码管理工具-git
    ES6笔记01
    07_查找、软链接、打包压缩、软件安装
    06_系统信息相关命令
    oracle序列中cache和nocache
    PL/SQL规范、块、过程、函数、包、触发器
    对Xcode菜单选项的详细探索(干货)
  • 原文地址:https://www.cnblogs.com/nemolmt/p/6694003.html
Copyright © 2011-2022 走看看