Editor

Create a Callable Formatter

Advanced · 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 Formatter class that takes a prefix and suffix in __init__. Define __call__ so that calling the object with a string wraps it with the prefix and suffix. Create Formatter('[', ']') and print the result of calling it with 'hello'. Then create Formatter('<<', '>>') and print the result of calling it with 'warning'.

# Create the Formatter class with __call__

More Magic Methods exercises

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