The library requires a class to store information about a book. Set up a class to hold data including title, author, year of publication, and a boolean variable to indicate if the book is in the library or if the book has been taken out. Create a method to load the data for one book. Create another method to display the data for a book. Create another method to check if a book is in the library or not. Write a main program to test your methods.
时间: 2023-12-30 09:07:00 浏览: 79
Here is a possible implementation of the book class and the main program:
```python
class Book:
def __init__(self, title, author, year, is_available):
self.title = title
self.author = author
self.year = year
self.is_available = is_available
def load_data(self):
self.title = input("Enter book title: ")
self.author = input("Enter book author: ")
self.year = int(input("Enter year of publication: "))
self.is_available = True
def display_data(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Year of publication: {self.year}")
print(f"Availability: {'in the library' if self.is_available else 'taken out'}")
def is_in_library(self):
return self.is_available
# main program
book1 = Book("The Catcher in the Rye", "J.D. Salinger", 1951, True)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 1960, False)
book1.display_data()
print(book1.is_in_library())
book2.load_data()
book2.display_data()
print(book2.is_in_library())
```
In this program, we define a Book class with four attributes: title, author, year, and is_available. The constructor initializes these attributes with the values passed as arguments.
The load_data() method prompts the user to enter the data for a book, and sets the corresponding attributes of the book object. The display_data() method prints the data for a book to the console. The is_in_library() method returns True if the book is in the library, False otherwise.
In the main program, we create two Book objects, book1 and book2, with different initial values for their attributes. We call the display_data() and is_in_library() methods to test the functionality of the class. We also call the load_data() method for book2 to demonstrate how it can be used to set the attributes of a book object.
阅读全文