从同一个模块中的类名字符串中获取python类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17959996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:36:28  来源:igfitidea点击:

Get python class object from class name string in the same module

python

提问by Chris McKinnel

I have a class

我有一堂课

class Foo():
    def some_method():
        pass

And another class in the same module:

同一模块中的另一个类:

class Bar():
    def some_other_method():
        class_name = "Foo"
        #can I access the class Foo above using the string "Foo"?

I want to be able to access the Fooclass using the string "Foo".

我希望能够Foo使用字符串“Foo”访问该类。

I can do this if I'm in another module by using:

如果我在另一个模块中,我可以使用以下方法执行此操作:

from project import foo_module
foo_class = getattr(foo_module, "Foo")

Can I do the same sort of thing in the same module?

我可以在同一个模块中做同样的事情吗?

The guys in IRC suggested I use a mapping dict that maps string class names to the classes, but I don't want to do that if there's an easier way.

IRC 中的人建议我使用映射字典将字符串类名映射到类,但如果有更简单的方法,我不想这样做。

采纳答案by khachik

import sys
getattr(sys.modules[__name__], "Foo")

# or 

globals()['Foo']

回答by user2357112 supports Monica

globals()[class_name]

Note that if this isn't strictly necessary, you may want to refactor your code to not use it.

请注意,如果这不是绝对必要的,您可能需要重构您的代码以不使用它。

回答by jh314

You can do it with help of sysmodule:

您可以在sys模块的帮助下完成:

import sys

def str2Class(str):
    return getattr(sys.modules[__name__], str)