Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

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

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 Foo class using the string "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import sys
getattr(sys.modules[__name__], "Foo")

# or 

globals()['Foo']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...