use __name__ as attribute

2020-05-29 03:22发布

问题:

i was reading a book about python class the main problem that i found that in an example in part of __str__ that he use a strange thing that he do

__class__.__name__

the full code is :

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

u can use self.class and it work the Writer comment for this part i mean __class__.__name__ he say .__name__ that is the string version of the class name can someone explain to my what Means

回答1:

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.