What Exactly is a Decorator?
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.
How Decorators Work
A decorator is simply a function that takes another function as input, adds some extra functionality, and returns a new function.
Example:
<span>def</span> <span>shout</span><span>(</span><span>func</span><span>):</span><span>def</span> <span>wrapper</span><span>():</span><span>return</span> <span>func</span><span>().</span><span>upper</span><span>()</span><span>return</span> <span>wrapper</span><span>@shout</span><span>def</span> <span>greet</span><span>():</span><span>return</span> <span>"</span><span>hello</span><span>"</span><span>print</span><span>(</span><span>greet</span><span>())</span> <span># Outputs: HELLO </span><span>def</span> <span>shout</span><span>(</span><span>func</span><span>):</span> <span>def</span> <span>wrapper</span><span>():</span> <span>return</span> <span>func</span><span>().</span><span>upper</span><span>()</span> <span>return</span> <span>wrapper</span> <span>@shout</span> <span>def</span> <span>greet</span><span>():</span> <span>return</span> <span>"</span><span>hello</span><span>"</span> <span>print</span><span>(</span><span>greet</span><span>())</span> <span># Outputs: HELLO </span>def shout(func): def wrapper(): return func().upper() return wrapper @shout def greet(): return "hello" print(greet()) # Outputs: HELLO
Enter fullscreen mode Exit fullscreen mode
Here, the @shout
decorator transforms greet()
so it returns its output in uppercase.
Common Use Cases for Decorators
Decorators are handy for adding cross-cutting functionalities to functions, like:
- Logging: Automatically logging whenever a function is called.
- Authentication: Checking permissions before running sensitive functions.
- Timing: Measuring how long a function takes to run.
Stacking Decorators
Yes, you can stack multiple decorators to apply multiple layers of functionality to a single function.
<span>@authenticate</span><span>@log</span><span>def</span> <span>process_data</span><span>(</span><span>data</span><span>):</span><span># Function code </span><span>@authenticate</span> <span>@log</span> <span>def</span> <span>process_data</span><span>(</span><span>data</span><span>):</span> <span># Function code </span>@authenticate @log def process_data(data): # Function code
Enter fullscreen mode Exit fullscreen mode
This runs authenticate
first, then log
, and finally process_data
.
Final Words: Decorators—Your Function’s Best Friend
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!”
原文链接:Python Decorators: Adding Magic to Your Functions, One Layer at a Time
暂无评论内容