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  
  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/nemolmt/p/6694003.html
Copyright © 2011-2022 走看看