In Python, after you've created an instance of a class, you are not limited to the values assigned during initialization. You can modify the attributes of an instance directly. For example, let's use our Book class from earlier. After creating a Book instance, you may want to update the number of pages or the author's name. You can achieve this by directly accessing the attribute using the dot operator ., and assigning a new value:
class Book:
def __init__(self, title, author, pages):
self.title = title # Assign title to the book instance
self.author = author # Assign author to the book instance
self.pages = pages # Assign number of pages to the book instance
self.is_read = False # Book has not been read yet
book1 = Book('To Kill a Mockingbird', 'Harper Lee', 281)
print(book1.pages) # 281
book1.pages = 324 # Update the number of pages
print(book1.pages) # 324
print(book1.author) # 'Harper Lee'
book1.author = 'Lee, Harper' # Update the author's name
print(book1.author) # 'Lee, Harper'
Challenge: Create a Book Class
Your task is to design a Book class with four attributes:
title: defaults to "Untitled Book"
author: defaults to "Unknown Author"
price: defaults to 0.0
quantity_in_stock: defaults to 0
The class should initialize all the attributes with these default values in its constructor. The class should also include a method display to display the current attributes of the book in a readable format. The format should be "Title: [title], Author: [author], Price: [price], Quantity in stock: [quantity_in_stock]".
The program will then take two lines of input. The first line contains the name of an attribute (title, author, price, quantity_in_stock). The second line contains a value for that attribute.
Your program should assign this new value to the attribute specified in the input, and then call the display method on the Book object to print out the book's current attributes.
Input
Output
title
War and Peace
Title: War and Peace, Author: Unknown Author, Price: 0.0, Quantity in stock: 0