Day 18: Decorators in Python
Enhancing Python Functionality: Unveiling the Power of Decorators
On the Eighteenth Day of Python Learning, Embark on the Journey of Decorators: Unlocking the Power of Functionality Extension. Decorators in Python serve as versatile design pattern, enabling modification or extension of function/method behavior without altering their source code.
Decorators
A decorator in Python is a design pattern that allows you to modify or extend the behavior of functions or methods without changing their source code. Essentially, decorators wrap another function and allow you to execute code before and/or after the wrapped function runs. The @decorator_name syntax indicates them and are commonly used for tasks such as logging, authentication, caching, and more.
Decorator to add extra print statements:
def decorator(func):
def internal_method():
print("Welcome to decorator function ")
func();
print("End of the function")
return internal_method
@decorator
def say_hello():
print("Hello Bro")
say_hello()
Here, we've crafted a decorator function designed to augment a method by returning its internal functionality while injecting additional print statements.
Decorator to add two numbers:
def decorator(func):
def new_method(*args, **kwargs):
print("Decorate my function")
func(*args, **kwargs)
print("second line")
return new_method
@decorator
def multiply(a, b):
print(a * b)
multiply(5, 10)
Conclusion
Decorators in Python offer a concise and powerful means to modify or extend the functionality of functions or methods without altering their source code directly. Through examples, we've demonstrated how decorators can enhance code readability and maintainability by seamlessly injecting additional behavior before or after function execution. By mastering decorators, developers can write more expressive and efficient Python code, making them a fundamental tool for building modular and maintainable software solutions.
Thankyou💕💕