2018年8月15日 星期三

[ Python 常見問題 ] import module from string variable

Source From Here 
Question 
Problem is that I can't find a way to instruct Python to load submodule from string. 

How-To 
The __import__ function can be a bit hard to understand. In Python 2.7 and Python 3.1 or later, you can use importlib. Supposed you have one module: 
- test.py 
  1. def add(a, b):  
  2.     return a + b  
  3.   
  4. def sub(a, b):  
  5.     return a - b  
  6.   
  7.   
  8. class Clz:  
  9.     def __init__(self, name):  
  10.         self.name = name  
  11.   
  12.     def __repr__(self):  
  13.         return self.__str__(self)  
  14.   
  15.     def __str__(self):  
  16.         return "Name={}".format(self.name)  
Then you can import it his way: 
>>> import importlib 
>>> modu_name = 'test' 
>>> modu = importlib.import_module(modu_name) 
>>> modu.add(1, 2) 
3 
>>> modu.sub(2, 1) 
1 
>>> obj = modu.Clz('john') 
>>> print(obj) 
Name=john

Some notes: 
* If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email") 
* You can't import anything if there is no __init__.py in the folder with file you are trying to 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...