Python でクラスを実装し、簡単な電子書籍を表す
簡単な電子書籍クラスを作成しますEBookこのクラスには、書名、著者、ページ数、現在のページ番号などの属性が含まれます。また、ページめくりや現在のページのコンテンツを取得するなどのメソッドも実装します。
実例
class EBook:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.current_page = 1
def next_page(self):
if self.current_page 1:
self.current_page -= 1
else:
print("You are already at the beginning of the book.")
def get_current_page_content(self):
return f"Page {self.current_page} of {self.pages}"
def __str__(self):
return f"'{self.title}' by {self.author}, {self.pages} pages"
# 使用例
book = EBook("Python Programming", "John Doe", 300)
print(book)
print(book.get_current_page_content())
book.next_page()
print(book.get_current_page_content())
book.previous_page()
print(book.get_current_page_content())
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.current_page = 1
def next_page(self):
if self.current_page 1:
self.current_page -= 1
else:
print("You are already at the beginning of the book.")
def get_current_page_content(self):
return f"Page {self.current_page} of {self.pages}"
def __str__(self):
return f"'{self.title}' by {self.author}, {self.pages} pages"
# 使用例
book = EBook("Python Programming", "John Doe", 300)
print(book)
print(book.get_current_page_content())
book.next_page()
print(book.get_current_page_content())
book.previous_page()
print(book.get_current_page_content())
コード解析:
__init__メソッド:電子書籍の属性(書名、著者、総ページ数、現在のページ番号)を初期化します。next_pageメソッド:現在のページ番号を1増やします。すでに最後のページの場合は、ユーザーに本の末尾に到達したことを知らせます。previous_pageメソッド:現在のページ番号を1減らします。すでに最初のページの場合は、ユーザーに本の最初にいることを知らせます。get_current_page_contentメソッド:現在のページ番号の内容を返します。__str__メソッド:電子書籍の基本情報(書名、著者、総ページ数)を返します。
出力結果:
'Python Programming' by John Doe, 300 pages Page 1 of 300 Page 2 of 300 Page 1 of 300その他の拡張
Python3 実例