且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从当前文件中通过 Python 中的字符串名称实例化类?

更新时间:2023-11-02 20:42:22

如果您在定义它们的同一模块上,您可以调用 globals(),并且只需使用类名作为键返回的字典:

If you are on the same module they are defined you can call globals(), and simply use the class name as key on the returned dictionary:

例如.mymodule.py

Ex. mymodule.py

class A: ...
class B: ...
class C: ...

def factory(classname):
    cls = globals()[classname]
    return cls()

如果您从另一个文件导入类,上述解决方案也适用

Above solution will also work if you are importing class from another file

否则,您可以简单地在您的函数中导入模块本身,并使用 getattr(这样做的好处是您可以将此工厂函数重构为任何其他模块而无需更改):

Otherwise, you can simply import the module itself inside your functions, and use getattr (the advantage of this is that you can refactor this factory function to any other module with no changes):

def factory(classname):
     from myproject import mymodule
     cls = getattr(mymodule, classname)
     return cls()