简体   繁体   English

Python 3.9 如果一个字符串匹配一个class的名字,实例化class(动态实例化具体的class)

[英]Python 3.9 if a string matches a class name, instantiate the class (instantiate a specific class dynamically)

I would like to instantiate a single class if a string var matches the name of the class. In similar questions, there seems to be a dependency that the name of the class is known at the start.如果字符串 var 与 class 的名称匹配,我想实例化一个 class。在类似的问题中,似乎有一个依赖项,即 class 的名称在一开始就已知。 In my case, I only know that the input string will match the name of a class. I want to use the string to identify which class (out of many choices) I need to instantiate.在我的例子中,我只知道输入字符串将匹配 class 的名称。我想使用该字符串来识别我需要实例化哪个 class(有很多选择)。 IE load the class with the same name as the string; IE加载与字符串同名的class;

If string-var == a class (in a module file) in a directory, instantiate that class.

I thought the new getattr would help, but that seems to be for methods/functions as opposed to a class itself.我认为新的 getattr 会有所帮助,但这似乎是针对方法/函数的,而不是 class 本身。 I also considered issubclass, but the parameter needs to be a class, not a string.我也考虑过issubclass,但是参数需要是class,不是字符串。 Any suggestions are greatly appreciated!非常感谢任何建议!

You should explicitly define an interface that maps a publicly known string to a reference to the class:您应该显式定义一个接口,将公开已知的字符串映射到对 class 的引用:

class Foo:
    ...

class Bar:
    ...

classes = {"foo": Foo, "bar": Bar}

Then you can lookup the appropriate class in the dict using your string (which, as you'll note, is not required to be the name of the class):然后你可以使用你的字符串在 dict 中查找适当的 class (你会注意到,它不需要是类的名称):

cls_name = "foo"

obj = classes[cls_name]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM