Let's say you define a class:
class MyClass:
def __str__(self):
return str(self.__class__)
If you try to print that class, look what you get:
>>> instance = MyClass()
>>> print(instance)
__main__.MyClass
That is because the string version of the class includes the module that it is defined in. In this case, it is defined in the module that is currently being executed, the shell, so it shows up as __main__.MyClass
. If we use self.__class__.__name__
, however:
class MyClass:
def __str__(self):
return self.__class__.__name__
instance = MyClass()
print(instance)
it outputs:
MyClass
The __name__
attribute of the class does not include the module.
Note: The __name__
attribute gives the name originally given to the class. Any copies will keep the name. For example:
class MyClass:
def __str__(self):
return self.__class__.__name__
SecondClass = MyClass
instance = SecondClass()
print(instance)
output:
MyClass
That is because the __name__
attribute is defined as part of the class definition. Using SecondClass = MyClass
is just assigning another name to the class. It does not modify the class or its name in any way.