Python implement a class representing a simple e-book

Document 对象参考手册Python3 Examples

We will create a simple e-book classEBookThis class contains attributes such as book title, author, page count, and current page number. We will also implement methods such as turning pages and getting current page content.

Example

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"

# Example usage
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())

Code analysis:

  1. __init__Method: Initialize the e-book's attributes, including book title, author, total pages, and current page number.
  2. next_pageMethod: Add 1 to the current page number; if it is already the last page, prompt the user that they have reached the end of the book.
  3. previous_pageMethod: Subtract 1 from the current page number; if it is already the first page, prompt the user that they are at the beginning of the book.
  4. get_current_page_contentMethod: Return the content of the current page.
  5. __str__Method: Return the basic information of the e-book, including title, author, and total pages.

Output result:

'Python Programming' by John Doe, 300 pages
Page 1 of 300
Page 2 of 300
Page 1 of 300

Document 对象参考手册Python3 Examples

Other extensions