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): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = 'abc' class AnotherSubClass(WrapperClass): var = 'def'
And an obvious error message:
>>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File '', line 1, in File '', line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>>
Thanks!
Classes aren’t special, they’re just values contained in variables. If you’ve said:
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:
(
locals()is also available for local variables; between them you shouldn’t ever need to use the awfuleval()to access variables.)However as David notes,
self.__class__is already theclassobj, so there’s no need to go running about fetching it from the global variables by name;self.__class__.varis fine. Although really: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.