Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ความแตกต่างระหว่าง str() และ repr() ใน Python

เอกสาร Python ระบุว่า __repr__ ใช้หา "Official" String Representation ของออบเจ็กต์ ส่วน __str__ ใช้หา "Informal" String Representation

print และ str() ใช้ __str__ ส่วน repr() ใช้ __repr__

ตัวอย่างกับ datetime

>>> import datetime
>>> today = datetime.datetime.now()

>>> str(today)
'2018-01-12 09:21:58.130922'  # อ่านง่าย เข้าใจง่าย

>>> repr(today)
'datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)'  # Official representation

>>> eval('datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)')
datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)  # สร้างกลับได้

eval() รับสตริงแปลงเป็นออบเจ็กต์ได้ เพราะ repr() คืนค่าที่ reconstruct ออบเจ็กต์ได้

สรุป: ทุกคลาสควรมี __repr__ และถ้าคิดว่าควรมี String Version ที่อ่านง่าย (เช่น datetime) ให้สร้าง __str__ ด้วย