Table of contents
Introduction
Welcome to my 59th blog post on the Python journey. On day 59, I learned about a Powerful tool that allows us to change the behaviour of functions and methods in Python. This is called 'decorators'. Let's dive into more details and understand the functioning of decorators in Python.
So let's get started......
Decorators
Decorators are a powerful tool that allows us to modify the behaviour of functions and methods in Python.
They allow us to extend the functionality of the function and methods without changing the source code of the same.
A decorator is a function that takes another function as an argument and returns a new function that modifies the behaviour of the original function.
The new function is referred to as a "decorated" function.
Syntax -
@decorator_function
def my_function():
pass
The @decorator_function notation is just a shorthand for the following code:
def my_function():
pass
my_function = decorator_function(my_function)
Example -
def greet(fx):
def mfx(*args, **kwargs):
print("Good Morning")
fx(*args, **kwargs)
print("Thanks for using this function")
return mfx
@greet
def hello():
print("Hello world")
@greet #decorator
def add(a, b):
print(a+b)
# greet(hello)() #no need to write @greet if using this line. This line hampers readability. better use @greet syntax type.
hello()
# greet(add)(1, 2)
add(1, 2)
Decorators are often used to add functionality, such as logging, memoization, and access control.
Resources Used
You can watch the video of Day#59 by clicking on the below link ๐๐๐๐๐
Conclusion
Thanks, guys for going through this blog post. On day 59, I learned about decorators that provide powerful and flexible features in Python to add functionality to functions and methods without modifying their source code. They help in reducing code duplication and make the code more readable and maintainable.
Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #59
See you in the next one.....
About Me
Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.
I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.
So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.