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 lessonCreate 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
- Add String Representations to a BookBeginner
- Build a Team with __len__Beginner
- Fix the Broken Equality CheckIntermediate
- Make a Gradebook IndexableIntermediate
- Predict the Magic Method OutputIntermediate
- Make Tasks Sortable by PriorityIntermediate
- Refactor a Playlist with Magic MethodsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz