• 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  
  • 相关阅读:
    返回一个随机数组中的子数组中的数相加最大的和
    四则运算二之结果
    四则运算二
    UVA 11741 Ignore the Blocks
    UVA 1408 Flight Control
    UVA 10572 Black & White
    CF1138D(545,div2) Camp Schedule
    UVA 1214 Manhattan Wiring
    UVA 11270 Tiling Dominoes
    BZOJ 3261 最大异或和
  • 原文地址:https://www.cnblogs.com/UnGeek/p/5233368.html
Copyright © 2020-2023  润新知