Python Decorators: A Simple Guide
Contents
Python Decorators: A Simple Guide
1 What is a Decorator?
A decorator in Python is a function that modifies the behavior of another function. It adds extra functionality without changing the original function code.
2 Why Use Decorators?
Decorators help you:
- Reuse code
- Keep functions clean
- Add logging, timing, or access control
- Make your code more readable
3 Basic Example
|
|
Output:
|
|
4 Decorator with Arguments
|
|
Output:
|
|
5 Real Use Case: Timing Function
|
|
Output:
|
|
6 Key Points
- Use
*args
and**kwargs
to accept any number of arguments - The decorator wraps the original function
- Decorators make code reusable and clean
- They are widely used in web frameworks, logging, and testing
(This article was created by Qwen AI)