Tài liệu Python: __repr__ trả về "official" string representation, __str__ trả về "informal" string representation.
print()vàstr()dùng__str__repr()dùng__repr__
Ví dụ với datetime
import datetime today = datetime.datetime.now() print(str(today)) # '2024-01-15 10:30:45.123456' - dễ đọc cho user print(repr(today)) # 'datetime.datetime(2024, 1, 15, 10, 30, 45, 123456)' - official, có thể eval()
Khôi phục object từ repr
>>> eval(repr(today)) datetime.datetime(2024, 1, 15, 10, 30, 45, 123456)
Quy tắc thiết kế
- Mọi class nên có
__repr__(unambiguous, ideallyeval(repr(x)) == x) - Thêm
__str__nếu cần dạng dễ đọc cho end-user - Mặc định:
__str__fallback về__repr__