Decorators is a way to modify functions dynamically by passing them as arguments to other functions. They are defined by @ followed by func-name.
@func-name
In some cases , we will be needing some steps to be executed before and after some functions. This case can be handled in two ways.
- Duplicating code in every functions.
- Dynamically modifying functions.
Step 2 is the decorator.
We need to understand that functions are the first class objects. They can be passed by reference, passed by arguments, return from another function, define inside another function.
Inorder to understand better , we shall cook omelete.
Ingridients: Egg (Main Function), Salt,Pepper,Vegetables(Arguments).
Take a tawa, break an egg (functionality) ; add some (arguments) salt, pepper, vegetables (if needed). Cook for 2 mins. Omelete is ready.
Now we have created the omelete . Likewise, we can make some veggies stuff, potato mash and other functionalities. For all these we may include bread to make it a complete dish (Bread Omelete, Sandwich, etc...).
def bread(omelete):
def inner():
print("Bread + ",end="")
omelete()
print("Bread ",end="")
return inner
@bread
def omelete():
print("Omelete + ",end="")
omelete()
Result ,
(base) syed@syed:~/Documents/Decorators$ python dec.py
Bread + Omelete + Bread
Here, bread is a common thing that is been included in all dishes mentioned above.
Bread = Decorator
Omelete = Function
Decorators (Breads) are used to remove the duplicate code in the code base.
If you like this, leave a like , comment and make a share .
Top comments (0)