Understanding Python Decorators: Definitions, Syntax, and Practical Use Cases
This article explains what Python decorators are, how they differ from ordinary closures, demonstrates multiple syntax forms—including basic, parameterized, and class‑based decorators—with complete code examples, and outlines common application scenarios such as logging, authentication, timing, and caching.
1. Definition of Decorators
A decorator is a function that adds extra functionality to an existing function; essentially it is a closure.
Features of decorators:
Do not modify the source code of the original function.
Do not change the way the original function is called.
Add additional behavior to the original function.
Distinguishing closures and decorators:
If a closure function has exactly one parameter and that parameter is a function, the closure is considered a decorator.
Write code following the Open‑Closed Principle: existing code should not be modified but can be extended.
2. Example Code
<code># 定义装饰器
def decorator(func):
def inner():
# 在内部函数里面对已有函数进行装饰
print('已添加登录认证')
func()
return inner
def comment():
print('发表评论')
# 调用装饰器对已有函数进行装饰,左边的 comment = inner
comment = decorator(comment)
# 调用方式不变
comment()</code>3. Syntactic Sugar for Decorators
When many functions need the same login‑validation logic, repeatedly writing func = decorator(func) becomes cumbersome. Python provides a syntactic sugar using the @ symbol.
<code># 定义装饰器
def decorator(func):
def inner():
# 在内部函数里面对已有函数进行装饰
print('已添加登录认证')
func()
return inner
@decorator # 等价于 comment = decorator(comment)
def comment():
print('发表评论')
# 调用方式不变
comment()</code>4. Execution Timing of Decorators
After a module is loaded, the decorator executes immediately, decorating the target function.
<code># 定义装饰器
def decorator(func):
print('装饰器执行了')
def inner():
# 在内部函数里面对已有函数进行装饰
print('已添加登录认证')
func()
return inner
@decorator
def comment():
print('发表评论')
# 运行结果
# 装饰器执行了</code>5. Uses of Decorators
5.1 Typical Scenarios
Measuring function execution time
Logging output information
5.2 Timing Example
<code>import time
def decorator(func):
def inner():
begin = time.time()
func()
end = time.time()
result = end - begin
print(f'函数执行完成耗时:{result}')
return inner
@decorator
def work():
for i in range(10000):
print(i)
work()</code>6. Generic Decorators
Generic decorators can wrap functions of any signature.
6.1 Decorating Functions with Parameters
<code>def decorator(func):
def inner(num1, num2):
print('正在努力执行加法计算')
func(num1, num2)
return inner
@decorator
def add_num(num1, num2):
result = num1 + num2
print(f'结果为:{result}')
add_num(1, 2)</code>6.2 Decorating Functions with Return Values
<code>def decorator(func):
def inner(num1, num2):
print('正在努力执行加法计算')
num = func(num1, num2)
return num
return inner
@decorator
def add_num(num1, num2):
result = num1 + num2
return result
result = add_num(1, 2)
print(f'结果为:{result}')</code>6.3 Decorating Functions with Variable Arguments
<code>def decorator(func):
def inner(*args, **kwargs):
print('正在努力执行加法计算')
# *args: positional arguments
# **kwargs: keyword arguments
num = func(*args, **kwargs)
return num
return inner
@decorator
def add_num(*args, **kwargs):
result = 0
for value in args:
result += value
for value in kwargs.values():
result += value
return result
result = add_num(1, 2, a=3)
print(f'结果为:{result}')</code>7. Stacking Multiple Decorators
When multiple decorators are applied, they are executed from the innermost to the outermost.
<code>def make_div(func):
print('make_div装饰器执行了')
def inner():
result = '<div>' + func() + '</div>'
return result
return inner
def make_p(func):
print('make_p装饰器执行了')
def inner():
result = '<p>' + func() + '</p>'
return result
return inner
@make_div
@make_p
def content():
return '人生苦短,我用python'
c = content()
print(c)</code>Output:
<code>make_p装饰器执行了
make_div装饰器执行了
<div><p>人生苦短,我用python</p></div></code>8. Decorators with Parameters
A decorator can accept its own arguments using an extra outer function.
<code>def return_decorator(flag):
def decorator(func):
def inner(a, b):
if flag == '+':
print('正在努力执行加法计算')
elif flag == '-':
print('正在努力执行减法计算')
func(a, b)
return inner
return decorator
@return_decorator('+')
def add_num(a, b):
result = a + b
print(result)
@return_decorator('-')
def sub_num(a, b):
result = a - b
print(result)
add_num(1, 2)
sub_num(1, 2)</code>Output:
<code>正在努力执行加法计算
3
正在努力执行减法计算
-1</code>9. Class‑Based Decorators
A class can be used as a decorator by implementing the __call__ method.
<code>class MyDecorator(object):
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
print('马上就有下班啦')
self.__func()
@MyDecorator
def show():
print('快要下雪啦')
show()</code>Output:
<code>马上就有下班啦
快要下雪啦</code>10. Common Application Scenarios
Collecting operation or error logs for functions
Validating function usage permissions
Measuring function execution time
Dynamic data fetching in ORM/DB models via property methods
Caching function results
Customizing function input/output (serialization/deserialization)
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.