In Python 3.5, how can the class name be assigned to a class variable? The obvious alternative is to hardcode the class name.
class Foo(object):
the_module = __name__
also_the_module = __module__
def name_of_module(self):
return __name__
def name_of_class(self):
return __class__.__name__
print("Foo.the_module= ", Foo.the_module)
print("Foo.also_the_module= ", Foo.also_the_module)
print("Foo.__name__= ", Foo.__name__) # what is desired but outside of class def
print("Foo().name_of_module=", Foo().name_of_module())
print("Foo().name_of_class= ", Foo().name_of_class()) # what is desired but inside a method
I tried getting the class from the first argument of a @classmethod
.
class Foo(object):
@classmethod
def class_name(cls):
return cls.__name__
# Both of these produce the correct response but neither
# can be used assign to a class variable
print("Foo.class_name()= ", Foo.class_name())
print("Foo().class_name()= ", Foo().class_name())
Unfortunately, this function cannot be called when assigning to a class variable. class = class_name
produces NameError: name 'class_name' is not defined
. my_class = Foo.class_name()
produces NameError: name 'Foo' is not defined
.
NOTE: Updated question to use the correct Python term "class variable" and not a static variable (reflecting my C++ background)