how to dynamically create an instance of a class in python?

后端 未结 7 1677
我寻月下人不归
我寻月下人不归 2020-12-01 06:09

I have list of class names and want to create their instances dynamically. for example:

names=[
\'foo.baa.a\',
\'foo.daa.c\',
\'foo.AA\',
 ....
]

def save(c         


        
7条回答
  •  甜味超标
    2020-12-01 06:34

    This worked for me:

    from importlib import import_module
    
    class_str: str = 'A.B.YourClass'
    try:
        module_path, class_name = class_str.rsplit('.', 1)
        module = import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as e:
        raise ImportError(class_str)
    

提交回复
热议问题