Decorators in Python
Decorators in Python
In the world of Python programming, decorators are like the hidden gems that make your code more elegant, readable, and efficient. They provide a way to modify or enhance the behavior of functions or methods without changing their source code.
Python Decorators
In Python, Decorators are a powerful and flexible way to modify the behavior of functions or methods. They are often used to add functionality to existing code without altering its structure. Decorators are essentially functions that take another function as input and return a new function that usually extends or enhances the behavior of the original function.
Decorator Function:
def my_decorator(func): def wrapper(): # Some code before the function is called func() # Some code after the function is called return wrapper
Here, `my_decorator` is a function that takes another function `func` as its argument and returns a new function called `wrapper`. The `wrapper` function can modify or extend the behavior of `func`.
Code 1:
def my_decorator(func): def wrapper(): print("Hello Prepsters") func() print("Welcome in PrepInsta") return wrapper @my_decorator def meeting(): print("Hello!") meeting()
Output :
Hello Prepsters
Hello!
Welcome in PrepInsta
Applications of Decorators
- Logging: To log information before or after a function is called.
- Authentication: To check if a user is authenticated before allowing access to a particular function.
- Timing: To measure the time it takes for a function to execute.
- Caching: To cache the results of a function to improve performance.
- Authorization: To check if a user has the necessary permissions to execute a function.
- Validation: To validate input arguments before a function is executed.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment