🎯 Difference between repr and str in Python
Em poucas palavras
O objetivo de
__repr__é ser inequívoco e voltado ao desenvolvedor, idealmente reproduzindo a chamada que cria o objeto e distinguindo, por exemplo,MyClass(3)deMyClass("3"). Já__str__é voltado ao usuário e deve ser legível, deixando claro o que o objeto é. A implementação padrão não serve para nenhum dos dois, pois mostra apenas o endereço na memória.
📝 Notas e Desenvolvimento
Theme/Proggramming/PythonTheme/Programming/PythonTheme/Programming/PythonThe main difference between Special Methods __str__ and __Repr__ no Python can be summarized as follows:
- The standard implementation is useless, in case it would be
<__ Main __. Classname Object at 0x8b7d0>- This representation indicates only the location of the object without giving details of what it is.
- The goal of
__repr__is to be unequivocal and focused on the uses of developers.- It is interesting to differentiate between
myclass (3)andmyclass (" 3 "). Try to have this representation equal to the call of the class.
- It is interesting to differentiate between
- The goal of
__str__is to be readable and as a focus on users- It is interesting to ensure that the user can understand exactly what the object is.
__str__of the container uses contained objects__repr__- In general
__str __ = __ repr__If nothing is specified otherwise.
- In general
:: Reference :: Python - What is the difference Between str and repr? -Stack Overflow