Python 装饰器小结

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/3 13:36
# @Author : Ropon
# @File : 12_02.py

# 装饰器

# def warpper(fn):
# def inner():
# print("装饰函数执行前")
# fn() #利用闭包让函数常驻内存
# print("装饰函数执行后")
# return inner
#
# def test_func():
# print("这是一个测试函数")
#
# test_func = warpper(test_func)
# test_func()

# 需要传入参数装饰器

# def warpper(fn):
# def inner(*args, **kwargs):
# print("装饰函数执行前")
# fn(*args, **kwargs) #利用闭包让函数常驻内存
# print("装饰函数执行后")
# return inner
#
# def test_func(name, age):
# print(f"这是一个测试函数, 姓名是:{name}, 年龄是:{age}")
#
# test_func = warpper(test_func)
# test_func("ropon", 18)

# 带返回值得装饰器

# def warpper(fn):
# def inner(*args, **kwargs):
# print("装饰函数执行前")
# ret = fn(*args, **kwargs) #利用闭包让函数常驻内存
# print("装饰函数执行后")
# return ret
# return inner
#
# def test_func(name, age):
# print(f"这是一个测试函数, 姓名是:{name}, 年龄是:{age}")
# return {"name": name, "age": age}
#
# test_func = warpper(test_func)
# res = test_func("ropon", 18)
# print(res)

# 带参数的装饰器

# def warpper_out(fn, flag):
# def warpper(*args, **kwargs):
# if flag:
# print("装饰函数执行前")
# ret = fn(*args, **kwargs) # 利用闭包让函数常驻内存
# print("装饰函数执行后")
# else:
# ret = fn(*args, **kwargs) # 利用闭包让函数常驻内存
# return ret
# return warpper
#
# def test_func(name, age):
# print(f"这是一个测试函数, 姓名是:{name}, 年龄是:{age}")
# return {"name": name, "age": age}
#
# test_func = warpper_out(test_func, True)
# res = test_func("ropon", 18)
# print(res)

# 语法糖 @

# def warpper_out(flag):
# def warpper(fn):
# def inner(*args, **kwargs):
# if flag:
# print("装饰函数执行前")
# ret = fn(*args, **kwargs) #利用闭包让函数常驻内存
# print("装饰函数执行后")
# else:
# ret = fn(*args, **kwargs) # 利用闭包让函数常驻内存
# return ret
# return inner
# return warpper
#
# @warpper_out(False)
# def test_func(name, age):
# print(f"这是一个测试函数, 姓名是:{name}, 年龄是:{age}")
# return {"name": name, "age": age}
#
# res = test_func("ropon", 18)
# print(res)

# 多个装饰器

# def warpper_out1():
# pass
#
# def warpper_out2():
# pass
#
# def warpper_out3():
# pass
#
#
# @warpper_out1
# @warpper_out2
# @warpper_out3
# def func():
# pass

# 执行流程
# warpper_out1
# warpper_out2
# warpper_out3
# func
# warpper_out3
# warpper_out2
# warpper_out1