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

ความแตกต่างระหว่าง __str__ และ __repr__ ใน Python

Built-in Functions repr() และ str() เรียก object.__repr__(self) และ object.__str__(self) ตามลำดับ ฟังก์ชันแรกคำนวณ Official Representation ฟังก์ชันที่สองคืน Informal Representation

ผลลัพธ์เหมือนกันสำหรับ Integer Object:

>>> x = 1
>>> repr(x)
'1'
>>> str(x)
'1'

แต่ต่างกันสำหรับ String Object:

>>> x = "Hello"
>>> repr(x)
"'Hello'"
>>> str(x)
'Hello'

Return Value ของ repr() ของ String สามารถ eval() ได้และได้ String Object ถูกต้อง แต่ str() ไม่ได้:

>>> y1 = repr(x)
>>> eval(y1)
'Hello'
>>> y2 = str(x)
>>> eval(y2)
NameError: name 'Hello' is not defined

สรุป: repr() คืน Default และ Unambiguous Representation ส่วน str() ให้ Informal Representation อ่านง่ายแต่อาจไม่ Unambiguous เสมอไป