Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

So sánh str() vs repr() trong Python

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, ideally eval(repr(x)) == x)
  • Thêm __str__ nếu cần dạng dễ đọc cho end-user
  • Mặc định: __str__ fallback về __repr__