2017年11月8日 星期三

[ Python 常見問題 ] Python dynamic instantiation from string name of a class

Source From Here 
Question 
In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows: 
loader-class script: 
  1. import sys  
  2. class loader:  
  3.   def __init__(self, module_name, class_name): # both args are strings  
  4.     try:  
  5.       __import__(module_name)  
  6.       modul = sys.modules[module_name]  
  7.       instance = modul.class_name() # obviously this doesn't works, here is my main problem!  
  8.     except ImportError:  
  9.        # manage import error  
Some-dynamically-loaded-module script: 
  1. class myName:  
  2.   # etc...  
I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules... 

How-To 
You can use getattr 
  1. getattr(module, class_name)  
to access the class. More complete code: 
  1. module = __import__(module_name)  
  2. class_ = getattr(module, class_name)  
  3. instance = class_()  
A simple example as below. Consider you have test.py in current path: 
  1. class Hello:  
  2.     def __init__(self, name):  
  3.         self.name = name  
  4.   
  5.     def hello(self):  
  6.         print("Hello {}".format(self.name))  
Then you can initialize the Hello class this way: 
>>> test_module = __import__('test') 
>>> helloClass = getattr(test_module, 'Hello') 
>>> helloObj = helloClass('John') 
>>> helloObj.hello() 
Hello John


沒有留言:

張貼留言

[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...