🎯 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) de MyClass("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) and myclass (" 3 "). Try to have this representation equal to the call of the class.
  • 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.

:: Reference :: Python - What is the difference Between str and repr? -Stack Overflow


📚 Referências e Fontes

🔗 Conexões do Cofre

🌐 Referências Externas

💬 Citações Diretas