Category: Python

Python – Decorator Class

Similar to Decorator functions we can define a decorator to be a class.

A decorator class has a special class method __call__(). This method is responsible for supporting a case when an object is called. The advantage of decorator class over function is they bring the OOP feature such as inherirtance etc.

In the below code snippet the the decorated function is assigned to the self.func i.e. to the decorator. The decorator class itself calls the decorated function.

Passing a message to the decorator class. Here the message is passed from the LogDecorator and initailised in the class constructor.

The calling method is accessible in the __call__() method.

Python- Decorator functions

Decorators are very useful for refactoring or debugging the code.

Decorators are used to but not limited to do the following –

  • validate the arguments
  • modiy the arguments
  • modify the returned objects
  • message logging
  • caching

See below code snippet calls the log function to the decorator method which returns the log function.

Other way to perform the same is by decorating the method with @decorator method which widely in Python

The above example can be rewritten with following code snippet. Here the calling function is decorated with log function which returns

Arguments passed to the deocrated function can also be made available to the decorator function using *args and **kwargs

See below example for same. Here the decorator calls the decorated function and prints the same. This way you can log the execution of decorated function. Log the time the parameters, output and time taken to execute the fucntion.

This way decorator function can be made global.