Python: Reference to a class from a string?

后端 未结 4 515
春和景丽
春和景丽 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:51

    How to use a string containing a class name to reference a class itself?

    Classes aren't special, they're just values contained in variables. If you've said:

    class X(object): pass
    

    in global scope, then the variable ‘X’ will be a reference to the class object.

    You can get the current script/module's global variables as a dictionary using ‘globals()’, so:

    classobj= globals()[self.__class__.__name__]
    print classobj.var
    

    (locals() is also available for local variables; between them you shouldn't ever need to use the awful eval() to access variables.)

    However as David notes, self.__class__ is already the classobj, so there's no need to go running about fetching it from the global variables by name; self.__class__.var is fine. Although really:

    print self.var
    

    would be the usual simple way to do it. Class members are available as members of their instances, as long as the instance doesn't overwrite the name with something else.

提交回复
热议问题