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


沒有留言:

張貼留言

[ Py DS ] Ch1 - IPython: Beyond Normal Python

Source From  Here   Keyboard Shortcuts in the IPython Shell   If you spend any amount of time on the computer, you’ve probably found a u...