__repr__() tính toán "official" string representation của object. repr() built-in dùng __repr__(). Trả về biểu diễn có thể in, một trong các cách tạo ra object này. __repr__() hữu ích cho developer, __str__() cho end-user.
Ví dụ
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)
Ví dụ datetime
import datetime today = datetime.datetime.now() print(repr(today)) # datetime.datetime(2024, 1, 15, 10, 30, 45, 123456) # Có thể eval() để tái tạo object eval(repr(today)) # datetime.datetime(2024, 1, 15, 10, 30, 45, 123456)
Quy tắc tốt
__repr__nên unambiguous, ideal:eval(repr(obj)) == obj- Format:
ClassName(attr=value, ...) - Dataclass (Python 3.7+) tự động sinh
__repr__