+ 3
Can anyone help what is the difference between str and rep in python
pls can you give useful examples.
7 ответов
+ 6
Unambigous means precise, accurate, not leaving doubts to what is what. For example: "May 7th, 2017", although we know it represents a date, is just a string to Python, unless you declare it a class of your own. Then you might define __repr__ to return a tuple or a list of day, month, year (so it can be clear what is what - use __repr__ and be as verbose as you like) and still wanting to print it out to the user as a string (that's basically what __str__ is for).
+ 9
In most of the cases, really vague.
__str__ is meant to give a human-readable string (mainly for printing), while __repr__ is thought to give the best, unambigous representation.
__str__ will return '100' from both a string '100' and a number 100 - it is readable but not unambigous.
__repr__ will differentiate what is what. If you put it as an argument to eval() method and give it an object as its own argument, the expression will return the very object.
Fortunately, both __str__ and __repr__ can be overridden and return whatever you need :)
+ 6
awesome explanations Kuba :)
+ 5
No problem, pls tick my answer with a ✅ if it helped you, TIA ;)
+ 3
thank you very much for your useful info..
pls could you explain what is unambiguous ?
+ 3
sure
+ 2
thanks..Kuba. really good explanation.