Python: Reference to a class from a string?

后端 未结 4 516
春和景丽
春和景丽 2020-12-11 10:51

How to use a string containing a class name to reference a class itself?
See this (not working) exemple...

class WrapperClass:
    def display_var(self):         


        
4条回答
  •  遥遥无期
    2020-12-11 11:32

    Depending on where you get this string, any general method may be insecure (one such method is to simply use eval(string). The best method is to define a dict mapping names to classes:

    class WrapperClass:
        def display_var(self):
            #FIXME: self.__class_name__.__name__ is a string
            print d[self.__class__.__name__].the_var
    
    class SomeSubClass(WrapperClass):
        the_var = "abc"
    
    class AnotherSubClass(WrapperClass):
        the_var = "def"
    
    d = {'WrapperClass': WrapperClass, 'SomeSubClass': SomeSubClass, 'AnotherSubClass': AnotherSubClass}
    AnotherSubClass().display_var()
    # prints 'def'
    

提交回复
热议问题