理解 python 的装饰器

Python decorator

Posted by gomyck on October 11, 2023

python 的装饰器类似于 java 的装饰器, 都是对方法的增强, 从这个角度出发, 我们看下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from functools import wraps

def decorator(arg):
    print(arg)
    def return_func(func):
        @wraps(func)
        def decorated(*args, **kwargs):
            if not can_run:
                return "Function will not run {}".format(args[0])
            return func(*args, **kwargs)
        return decorated
    return return_func

@decorator(arg='123123')
def test_func(xxx):
    return ("Function is running {}".format(xxx))


can_run = True
print(test_func(11111))
# Output: Function is running 11111

can_run = False
print(test_func(22222))
# Output: Function will not run 22222

print(test_func.__name__)
# Output: test_func

装饰器运行原理:

  • 先运行 @decorator(arg=’123123’) 返回了一个装饰器: return_func
  • 把函数 test_func 传入到第一步返回的装饰器里: return_func(func)
  • wraps 的作用是: 保留被装饰的函数原有的属性