Modify Attributes

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 = 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(           # 'Harper Lee' = 'Lee, Harper'  # Update the author's name
print(           # '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 __init__ method should not take any arguments). 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.
title War and Peace
Title: War and Peace, Author: Unknown Author, Price: 0.0, Quantity in stock: 0
quantity_in_stock 20
Title: Untitled Book, Author: Unknown Author, Price: 0.0, Quantity in stock: 20


Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue