Editor

Add String Representations to a Book

Beginner · Write the code · from Python Magic Methods: The Complete __dunder__ Guide

From the lesson: Python Magic Methods: The Complete __dunder__ Guide

Think of a TV remote control. You press the volume button, and the TV gets louder. You press the channel button, and it switches channels. You don't think about how it works - you just press the button and the TV responds.

Read the lesson

Create a Book class with title and author attributes. Add __str__ that returns '<title> by <author>' and __repr__ that returns 'Book(\'<title>\', \'<author>\')'. Create Book('1984', 'Orwell') and print it using both str() and repr().

# Create the Book class with __str__ and __repr__

More Magic Methods exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz