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  
  • 相关阅读:
    [MFC美化] Skin++使用详解-使用方法及注意事项
    [MFC美化] SkinMagic使用详解3- 常见使用问题解答
    [MFC美化] SkinMagic使用详解2- SkinMagic常用函数介绍
    [MFC美化] SkinMagic使用详解1- SkinMagic使用流程
    MFC 自定义控件
    error C3872: “0x3000”: 此字符不允许在标识符中使用
    websocket学习
    Servlet学习1
    Git使用学习
    异常捕获测试
  • 原文地址:https://www.cnblogs.com/nemolmt/p/6694003.html
Copyright © 2011-2022 走看看