Python Programming - Objects - Discussion

Discussion Forum : Objects - General Questions (Q.No. 28)
28.
Consider the following Python code:
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"{self.title} by {self.author}"
If you create an instance of the `Book` class called my_book with title "The Great Gatsby" and author "F. Scott Fitzgerald", what will be the result of calling str(my_book)?
"The Great Gatsby F. Scott Fitzgerald"
"F. Scott Fitzgerald The Great Gatsby"
"The Great Gatsby by F. Scott Fitzgerald"
"F. Scott Fitzgerald by The Great Gatsby"
Answer: Option
Explanation:
The __str__ method provides a human-readable string representation of the object, and calling str(my_book) returns the specified format.
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.