2020年9月25日 星期五

[ Python 常見問題 ] Dynamic creation from string name of a class in dynamically imported module?

 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
  1. class MyClass:  
  2.     def __init__(self, name, age):  
  3.         self.name = name  
  4.         self.age = age  
  5.   
  6.     def __str__(self):  
  7.         return f"My name is {self.name} and my age is {self.age}"  
The default way to use this module:
>>> from my_mod import *
>>> john = MyClass('John', 40)
>>> print(john)
My name is John and my age is 40

To access the module my_mod and create object of class MyClass dynamically:
>>> my_mod = __import__('my_mod')
>>> my_clz = getattr(my_mod, 'MyClass')
>>> john = my_clz('John', 40)
>>> print(john)
My name is John and my age is 40
Or you can leverage another package importlib:
  1. import importlib  
  2. module = importlib.import_module(module_name)  
  3. class_ = getattr(module, class_name)  
  4. instance = class_()  


沒有留言:

張貼留言

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