Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python implementing a class representing a simple e-book

Python implementing a class representing a simple e-book

Document Object Reference Manual Python3 Examples

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

:

           

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 title, author, total pages, and current page number.
  2. next_page Method: 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.
  3. previous_page Method: 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.
  4. get_current_page_content Method: 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 Object Reference Manual Python3 Examples