Activity: Classes

Create a new class called Book. The class should have the following attributes:

  1. Create a constructor (an __init__ method) that initializes the attributes above when a Book object is created. Test your code by a few instances of the Book class.
    book1 = Book("1984", "George Orwell", 1949)
    book2 = BookI("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1981)
    
  2. Define a method as part of the Book class called check_out that changes is_checked_out to True and prints a message saying the book has been checked out. If the book has already been checked out, it should print a message indicating that. Test your code by calling it.

     book1.check_out()
    
     # Calling it a second time would trigger a different print statement that the book is already checked out
     book1.check_out()
    

    would output

     1984 by George Orwell has been checked out.
    
     1984 is already checked out.
    
  3. Define a method as part of the Book class called return_book that changes is_checked_out to False and prints a message saying the book has been returned. If the book has already been returned, it should print a message indicating that. Test your code by calling it.
     # Check out and return book
     book2.check_out()
     book2.return_book()
    
     # Returning it a second time would trigger the other print statement that the book is already in the library
     book2.return_book()
    

    would output

     The Hitchhiker's Guide to the Galaxy by Douglas Adams has been checked out
    
     The Hitchhiker's Guide to the Galaxy by Douglas Adams has been returned.
    
     The Hitchhiker's Guide to the Galaxy is already in the library.
    
  4. Define a method as part of the Book class called display_info that prints out all the details of the book, including whether it’s checked out or available. Call your function to test it. For example,
    book2.display_info()
    

    would output

    TItle: The Hitchhiker's Guide to the Galaxy
    Author: Douglas Adams
    Year Published: 1981
    Status: Available
    

If you finish early

  1. Create a new class, Library, which manages a collection of Book options. Include methods to add books, remove books, and display all books in the library.

  2. Create a new function of the Library class called collection(startYear, endYear) which returns a list of books from the library in which the publication year falls within the given range.

  3. Work on your final project with your group.

How to submit

Submit your working python file to Moodle.