Sobes.tech
Junior

Can you create a decorator from a class?

sobes.tech AI

Answer from AI

Yes, it is possible. The class should implement the __call__() method, which will be executed when an instance of the class is called as a function. An instance of this class can be used as a decorator.

class MyDecorator:
    def __init__(self, func):
        self._func = func

    def __call__(self, *args, **kwargs):
        # Code to execute before calling the decorated function
        print("Before calling the function")
        result = self._func(*args, **kwargs)
        # Code to execute after calling the decorated function
        print("After calling the function")
        return result

@MyDecorator
def my_function(x, y):
    return x + y

# Calling the decorated function
result = my_function(1, 2)
print(f"Result: {result}")

In this example:

  • MyDecorator is a class that acts as a decorator.
  • __init__ takes the function to be decorated.
  • __call__ wraps the call to the decorated function, allowing you to add logic before and after its execution.
  • @MyDecorator above my_function applies the MyDecorator class as a decorator.