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. How to do it?
HowTo
You can use getattr to access the attributes of loaded module. Consider you have module below:
- my_mod.py
The default way to use this module:
To access the module my_mod and create object of class MyClass dynamically:
Or you can leverage another package importlib:
In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. How to do it?
HowTo
You can use getattr to access the attributes of loaded module. Consider you have module below:
- my_mod.py
- class MyClass:
- def __init__(self, name, age):
- self.name = name
- self.age = age
- def __str__(self):
- return f"My name is {self.name} and my age is {self.age}"
To access the module my_mod and create object of class MyClass dynamically:
Or you can leverage another package importlib:
- import importlib
- module = importlib.import_module(module_name)
- class_ = getattr(module, class_name)
- instance = class_()
沒有留言:
張貼留言