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  
  • 相关阅读:
    票房和口碑称霸国庆档,用 Python 爬取猫眼评论区看看电影《我和我的家乡》到底有多牛
    用 Python 写个七夕表白神器
    3. GC复制算法
    一个粗糙的RPC框架设计思路
    503Service Unavailable
    centos 7.8下载地址
    海康摄像头SDK在Linux、windows下的兼容问题(二)已解决
    海康摄像头SDK在Linux、windows下的兼容问题
    二重指针
    【JavaScript 对象03】
  • 原文地址:https://www.cnblogs.com/UnGeek/p/5233368.html
Copyright © 2011-2022 走看看