如何从当前文件中通过 Python 中的字符串名称实例化类? [英] How to instantiate class by it's string name in Python from CURRENT file?

查看:23
本文介绍了如何从当前文件中通过 Python 中的字符串名称实例化类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 myfile.py 里面定义了一些类 ABC.现在我想通过它在 str 中的名称实例化类.我不明白要传递给 getattr 什么才能做到这一点.所有这样的例子都假设类在其他模块中:

Suppose I have myfile.py with some classes A, B and C defined INSIDE it. Now I want to instantiate class by it's name in str. I don't understand what to pass to getattr in order to do this. All examples like this assume that classes are in other module:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()

但我没有module_name.

推荐答案

如果您在定义它们的同一模块上,您可以调用 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()

这篇关于如何从当前文件中通过 Python 中的字符串名称实例化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆