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:
Some-dynamically-loaded-module script:
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
to access the class. More complete code:
A simple example as below. Consider you have
test.py in current path:
Then you can initialize the
Hello class this way:
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:
- import sys
- class loader:
- def __init__(self, module_name, class_name): # both args are strings
- try:
- __import__(module_name)
- modul = sys.modules[module_name]
- instance = modul.class_name() # obviously this doesn't works, here is my main problem!
- except ImportError:
- # manage import error
- class myName:
- # etc...
How-To
You can use getattr
- getattr(module, class_name)
- module = __import__(module_name)
- class_ = getattr(module, class_name)
- instance = class_()
- class Hello:
- def __init__(self, name):
- self.name = name
- def hello(self):
- print("Hello {}".format(self.name))
沒有留言:
張貼留言