Python implementing a class representing a simple e-book
We will create a simple e-book class EBook, which includes attributes such as title, author, page count, and current page number. We will also implement some methods, such as turning pages and getting the 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
:
(
"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
)
(
book
)
(
book.
get_current_page_content
(
)
)
book.
next_page
(
)
(
book.
get_current_page_content
(
)
)
book.
previous_page
(
)
(
book.
get_current_page_content
(
)
)
Code analysis:
__init__Method: initialize the e-book's attributes, including title, author, total pages, and current page number.next_pageMethod: increment the current page number by 1; if it is already the last page, prompt the user that they have reached the end of the book.previous_pageMethod: decrement the current page number by 1; if it is already the first page, prompt the user that they are at the beginning of the book.get_current_page_contentMethod: return the content of the current page.__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
Python3 Examples