In Java, overrides toString() method in the your class can change the textual representation of the object. The equivalent in Python is __str__ and __repr__. The important differences are:
- the goal of __repr__ is to be unambiguous
- the goal of __str__ is to be human-readable.
- str(object) calls the object's __str__ method
- repr(object) calls the object's __repr__ method
- by default, if __repr__ is defined and __str__ is not, calls to __str__ will be redirected to __repr__
- __repr__: representation of python object usually eval will convert it back to that object
- __str__: is whatever you think is that object in text form
- str(list) calls the list elements' _repr_ methods. Therefore, to make a list of objects human-readable, you need to override __repr__, or use list comprehension like:
[str(elem) for elem in list]
..
No comments:
Post a Comment