Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsSeniorOccasionalPractical

How can a class be used as a decorator instead of a nested function, and when is that approach preferable?

Answer

A class becomes usable as a decorator by implementing `__init__` to receive the decorated function and `__call__` to receive the call-time arguments and invoke the stored function, since `@MyDecorator` applied to a function is just `func = MyDecorator(func)`, and later calling `func(...)` becomes `instance.__call__(...)`. A class-based decorator is preferable when the decorator needs to hold and manage meaningful internal state across calls (like a call counter or a cache), since that state naturally lives as instance attributes instead of awkwardly nested closure variables.

Strong answer includes

  • __init__ receives the function, __call__ handles invocation
  • @MyDecorator on a function equals func = MyDecorator(func)
  • preferable when the decorator needs to hold real internal state

Practical example

Python example
class CountCalls:
    def __init__(self, func):
        self.func = func
        self.calls = 0
    def __call__(self, *a, **kw):
        self.calls += 1
        return self.func(*a, **kw)

exposes `decorated_func.calls` directly as instance state.

#decorators#oop

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols