use __name__ as attribute

血红的双手。 提交于 2020-01-22 10:31:17

问题


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.



来源:https://stackoverflow.com/questions/36367736/use-name-as-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!