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

Chuyển object thành expression string trong Python

str() chuyển object thành string readable. repr() chuyển thành expression string (unambiguous, dùng để recreate object).

Ví dụ datetime

import datetime
today = datetime.datetime.now()
str(today)   # '2018-04-08 11:25:36.918979'
repr(today)  # 'datetime.datetime(2018, 4, 8, 11, 25, 36, 918979)'

__str__ cho human-readable, __repr__ cho developer/debugging (official representation).