Python Decorators [Part 4]

Decorators as Classes

Sumeet Sarkar
1 min readDec 4, 2018

Python decorators [Part 3] we learnt to write decorators as functions, here we understand how to declare decorators as python classes

This is quite straight forward, and might even appear to be more easier to understand.

Let us see a simple class decorator and what gets called, in what order.

We can see that the class Decorator is applied on my_function. As soon as the decorator is applied over a function, the __init__ of the class is invoked.

__init__ receives the function as argument.

And upon execution of the my_function , __call__ of the class is invoked

Let us implement a practical example of Memoizing a function written to generate fibonacci series.

With this article I wrap up my python decorator series. Next I would start on Python Context Managers!

Let me know in the comments your feedbacks and how to make the series more engaging in future, or things to improve. All feedbacks are welcome!

--

--

Sumeet Sarkar

All things Javascript & Python. Love problem solving. I am also a photographer, foodie, impatient, philosophical. Engineering @ Postman