+ 3

The different between __str__ and __repr__ on Python3

did you know the different between __str__ and __repr__ on Python3?

13th Feb 2018, 9:50 AM
Fajar Kurniawan
3 ответов
+ 2
Here is a code you can play with and see the differences: https://code.sololearn.com/ch7OpLKai1Z7/?ref=app EDITED: This is what the official documentation says: object.__repr__(self) built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. object.__str__(self) to compute the “informal” or nicely printable string representation of an object. The return value must be a string object. This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used. The default implementation defined by the built-in type object calls object.__repr__().
13th Feb 2018, 10:44 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
Thank you everyone, especially to @Ulisses Cruz
13th Feb 2018, 12:25 PM
Fajar Kurniawan
+ 1
__str__ return byte string, while __repr__ return unicode (utf8) string...
13th Feb 2018, 10:44 AM
visph
visph - avatar