← Back to challenges

Pagination Class with OOP

PythonHardmathobjectsnumbersclasses

Instructions

Your task is to create a class to handle paginated content in a website. A pagination is used to divide long lists of content in a series of pages.

Example

The pagination class will accept 2 parameters:

  1. items (default: []): A list of contents to paginate.

  2. pageSize (default: 10): The amount of items to show in each page.

So for example we could initialize our pagination like this:

alphabetList = "abcdefghijklmnopqrstuvwxyz".split('')

p = Pagination(alphabetList, 4)

And then use the method getVisibleItems to show the contents of the paginated list.

p.getVisibleItems() # ["a", "b", "c", "d"]

You will have to implement various methods to go through the pages such as:

  • prevPage
  • nextPage
  • firstPage
  • lastPage
  • goToPage

Here's a continuation of the example above using nextPage and lastPage:

p.nextPage()

p.getVisibleItems()
# ["e", "f", "g", "h"]

p.lastPage()

p.getVisibleItems()
# ["y", "z"]

Notes

  • The second argument (pageSize) could be a float, in that case just convert it to an int (this is also the case for the goToPage method)
  • The methods used to change page should be chainable, so you can call them one after the other like this: p.nextPage().nextPage()
  • Please set the p.totalPages and p.currentPage attributes to the appropriate number as there cannot be a page 0.
  • If a page is outside of the totalPages attribute, then the goToPage method should go to the closest page to the number provided (e.g. there are only 5 total pages, but p.goToPage(10) is given: the p.currentPage should be set to 5; if 0 or a negative number is given, p.currentPage should be set to 1).
  • Please remove the comments I provided before publishing your solution.
python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.