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

str() vs repr() ใน Python: ความแตกต่างสำคัญ

ทั้ง str() และ repr() คืน string representation ของออบเจกต์ แต่มีจุดประสงค์ต่างกัน

คำอธิบายจาก Python Docs

  • str(): "informal" / readable representation สำหรับ end-user
  • repr(): "official" representation ที่สามารถนำไป eval() ได้กลับเป็นออบเจกต์เดิม

ตัวอย่างเปรียบเทียบ

>> str(123)
'123'
>>> repr(123)
'123'
# int: ไม่ต่างกัน

>>> str('Python')
'Python'
>>> repr('Python')
"'Python'"
# str: ต่างกัน! repr ใส่ quote ให้ eval ได้

>>> x = "Python"
>>> repr(x)
"'Python'"
>>> eval(repr(x)) == x
True

>>> eval(str(x))  # NameError: name 'Python' is not defined

ตัวอย่าง datetime

>> import datetime
>>> now = datetime.datetime.now()
>>> str(now)
'2019-03-29 01:29:23.211924'
>>> repr(now)
'datetime.datetime(2019, 3, 29, 1, 29, 23, 211924)'
# repr ให้โค้ดสร้างออบเจกต์เดิมได้

สรุปความแตกต่าง

str()repr()
ทำให้อ่านง่าย (human-readable)เป็นโค้ดสร้างออบเจกต์ใหม่ได้ (unambiguous)
สำหรับ End Userสำหรับ Developer / Debugging
default: __str__fallback: __repr__

เมื่อเขียน Class เอง

  • Implement __repr__ ให้สมบูรณ์ (eval ได้กลับมาเป็นตัวเดิม)
  • Implement __str__ ให้อ่านง่าย สวยงาม
  • ถ้าไม่เขียน __str__ จะ fallback ไป __repr__