Member-only story
🔥 Day 45 of #100DaysOfCode in Python: Mastering the Magic of Decorators
Welcome to Day 45! Today's focus is on one of Python's most elegant features: decorators. Decorators allow you to modify or enhance the behavior of functions or methods in a clean, concise, and readable way.
1. Understanding Decorators
In Python, a decorator is a design pattern that allows you to add new functionality to an existing object (like a function or a method) without modifying its structure. This is done by "wrapping" the object with a decorator, thereby enhancing its behavior or replacing it with a completely new one.
2. How Decorators Work
A decorator in Python is essentially a callable object (like a function) that takes another function as an argument and extends its functionality, returning the modified function.
3. Creating a Basic Decorator
Let's start with a simple example to understand how to create and use decorators:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()