Predict the Magic Method Output
Intermediate · Predict the output · 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 lessonRead the code carefully and predict exactly what gets printed. Pay attention to which magic method is called in each situation.
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
def __bool__(self):
return self.count > 0
def __repr__(self):
return f'Counter({self.count})'
c = Counter()
print(bool(c))
c()
c()
c()
print(c())
print(bool(c))
print(c)
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
- Make Tasks Sortable by PriorityIntermediate
- Create a Callable FormatterAdvanced
- Refactor a Playlist with Magic MethodsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz