use __name__ as attribute

21,668

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.

Share:
21,668
zerocool
Author by

zerocool

Updated on August 12, 2021

Comments

  • zerocool
    zerocool over 2 years

    I was reading a book about python class, but I found something strange in an example when defining __str__:

    __class__.__name__
    

    The full code is :

    def __str__(self):
    return '{} {},HP:{},xp:{}'.format(self.col.title(),self.__class__.__name__,self.points,self.exp)
    

    You can use self.class and it would work, although the writer does comment about this part. He says .__name__ is the string version of the class name. Can someone explain to me what that means ?