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

ฟังก์ชัน repr() ใน Python OOP ทำอะไร

เอกสาร Python ระบุว่า __repr__() คำนวณ Official String Representation ของออบเจ็กต์ ฟังก์ชัน repr() ใช้ __repr__() แสดงออบเจ็กต์ __repr__() คืน Printable Representation หนึ่งในวิธีที่สร้างออบเจ็กต์นั้นได้ __repr__() เหมาะสำหรับ Developer ส่วน __str__() สำหรับ End User

ตัวอย่าง

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return 'Point(x=%s, y=%s)' % (self.x, self.y)

p = Point(3, 4)
print(p)  # Point(x=3, y=4)

ตัวอย่างเพิ่มเติมกับ datetime

>>> import datetime
>>> today = datetime.datetime.now()
>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'

>>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)')
datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)

eval() แปลงสตริงจาก repr() กลับเป็นออบเจ็กต์ได้