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

前端 未结 3 394
迷失自我
迷失自我 2020-12-01 03:43

I have a class

class Foo():
    def some_method():
        pass

And another class in the same module:

clas         


        
相关标签:
3条回答
  • 2020-12-01 03:59
    import sys
    getattr(sys.modules[__name__], "Foo")
    
    # or 
    
    globals()['Foo']
    
    0 讨论(0)
  • 2020-12-01 03:59
    globals()[class_name]
    

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

    0 讨论(0)
  • 2020-12-01 04:02

    You can do it with help of sys module:

    import sys
    
    def str2Class(str):
        return getattr(sys.modules[__name__], str)
    
    0 讨论(0)
提交回复
热议问题