How to create an object by getting the name of a class from a string (the class is in another module)?
2 answers
To load a module dynamically and create an object from a string:
import importlib modulename, dot, classname = "pkg.your_module.ClassName".rpartition('.') module = importlib.import_module(modulename) klass = getattr(module, classname) instance = klass() |
If in the forehead, I would do this:
testClass.py
class TestClass(object): def __init__(self): self.name = "Hello, TestClass!" testImport.py
moduleName = "testClass" className = "TestClass" exec("from " + moduleName + " import " + className) exec("fileObject =" + className + "()") print fileObject.name Test
>>> python testImport.py >>> Hello, TestClass! But this trash code, IMHO. In general, I would look at other implementations, I thought many times to write a system of plug-ins for my program.
- Yes. Not really. - vladislavxbb
- 2I just leave it here at stackoverflow.com/questions/2226330/… ... stackoverflow.com/questions/301134/… - etki
- oneFike, thank you. - WorldCount
- Fike, thank you. - vladislavxbb
|