Back
+15 XP
Concept

Class-Based Decorators with __call__

Any class implementing `__call__` can serve as a decorator. Classes excel when a decorator must manage internal state or track metrics across invocations 🏛️.

python
class CallCounter:
    def __init__(self, func):
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call #{self.count} to {self.func.__name__} ⚡")
        return self.func(*args, **kwargs)

@CallCounter
def ping():
    return "pong"

ping()
ping()

# 38. Class-Based Decorators with __call__ Any class implementing `__call__` can serve as a decorator. Classes excel when a decorator must manage internal state or track metrics across invocations 🏛️. ```python class CallCounter: def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 print(f"Call #{self.count} to {self.func.__name__} ⚡") return self.func(*args, **kwargs) @CallCounter def ping(): return "pong" ping() ping() ``` When decorated with `@CallCounter`, `ping` becomes an instance of `CallCounter`. Calling `ping()` invokes `CallCounter.__call__()` with full access to `self.count`! 🏛️ --- ### Question Which dunder method allows a class instance to act as a callable decorator? 🧠 - [ ] a. `__call__` 🏛️ - [ ] b. `__invoke__` - [ ] c. `__run__` - [ ] d. `__execute__` --- ### Challenge Write class `ExecutionCounter` with `__init__(self, func)` initializing `self.invocations = 0`. Increment `self.invocations` inside `__call__` before returning `self.func(*args, **kwargs)`. Decorate `def log_event(): pass`. Call `log_event()` 3 times and print `log_event.invocations`. 🎯 <details> <summary>Solution</summary> ```python class ExecutionCounter: def __init__(self, func): self.func = func self.invocations = 0 def __call__(self, *args, **kwargs): self.invocations += 1 return self.func(*args, **kwargs) @ExecutionCounter def log_event(): pass log_event() log_event() log_event() print(log_event.invocations) ``` </details>

Checkpoint

Which dunder method allows a class instance to act as a callable decorator? 🧠

Practice

Write class `ExecutionCounter` with `__init__(self, func)` initializing `self.invocations = 0`. Increment `self.invocations` inside `__call__` before returning `self.func(*args, **kwargs)`. Decorate `def log_event(): pass`. Call `log_event()` 3 times and print `log_event.invocations`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks