Nếu lớp không định nghĩa cả repr () và str () thì kết quả trả về có dạng main .Class name object at 0x1025c4ed0

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

odyssey = Book("The Odyssey", "Homer")

print(odyssey)
print(repr(odyssey))
print(str(odyssey))
<__main__.Book object at 0x1025c4ed0>

This output is the default string representation of an object that’s inherited from the object class. The object class is the base class for all Python classes. It shows:

  • __main__.Book: The name of the class and where it’s defined
  • 0x1025c4ed0: The memory address of the object

Nguồn:: Real Python, When Should You Use .__repr__() vs .__str__() in Python? – Real Python


Cập nhật lần cuối : 30 tháng 6, 2024
Tạo : 3 tháng 11, 2023