【ときどきpython】__repr__をつかう
__repr__を使わない
code:main.py
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# 使用例
book = Book("Python Essentials", "Jane Doe", 22)
print(f'title: {book.title}, author: {book.author}, pages: {book.pages}')
このようにデバッグがめんどくさい
__repr__を使う
code:main.py
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"Book('{self.title}', '{self.author}', {self.pages})"
# 使用例
book = Book("Python Essentials", "Jane Doe", 22)
print(book)
シンプル