A decorator in Python is a powerful tool that allows you to wrap extra functionality around an existing function. Think of it as putting an extra layer of “awesome” on a function, without actually changing the original code.
A decorator is simply a function that takes another function as input, adds some extra functionality, and returns a new function.
Example:
def shout(func): def wrapper(): return func().upper() return wrapper @shout def greet(): return "hello" print(greet()) # Outputs: HELLO
Here, the @shout decorator transforms greet() so it returns its output in uppercase.
Decorators are handy for adding cross-cutting functionalities to functions, like:
Yes, you can stack multiple decorators to apply multiple layers of functionality to a single function.
@authenticate @log def process_data(data): # Function code
This runs authenticate first, then log, and finally process_data.
Decorators let you add power to your code without clutter. They’re your shortcut to clean, reusable, and enhanced functions.
? Here’s to functions that do more, without the mess!"
The above is the detailed content of Python Decorators: Adding Magic to Your Functions, One Layer at a Time. For more information, please follow other related articles on the PHP Chinese website!