Skip to content

Commit 88372ef

Browse files
author
gzliuxin
committed
add decorator examples
1 parent 14f712b commit 88372ef

File tree

2 files changed

+86
-5
lines changed

2 files changed

+86
-5
lines changed

decorator.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from flask import Flask
2+
app = Flask(__name__)
3+
4+
@app.route('/')
5+
def index():
6+
return 'Hello, World'
7+
8+
@app.route('/home')
9+
def home():
10+
return 'Welcome Home'
11+
12+
13+
from functools import wraps
14+
15+
16+
def debug(f):
17+
@wraps(f)
18+
def debug_function(*args, **kwargs):
19+
print('call: ', f.__name__, args, kwargs)
20+
ret = f(*args, **kwargs)
21+
print('return: ', ret)
22+
return debug_function
23+
24+
25+
@debug
26+
def foo(a, b, c=None):
27+
print(a, b, c)
28+
return True
29+
30+
31+
if __name__ == '__main__':
32+
foo(1, 2, 3)
33+
app.run()

patterns.md

Lines changed: 53 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Python Design Patterns
1010

1111
## 设计模式六大原则
1212

13+
1314
1. 单一职责原则
1415
* 一个类只做一件事情,模块化
1516

@@ -33,7 +34,7 @@ Python Design Patterns
3334
* 尽量在不修改源代码的情况下进行扩展
3435

3536

36-
> 扩展阅读:http://www.uml.org.cn/sjms/201211023.asp
37+
> 其实以上的原则不限于类的设计,很多工程上的系统设计也适用。
3738
3839

3940
## 常用设计模式
@@ -84,7 +85,7 @@ if __name__ == '__main__':
8485
class Shape(object):
8586
@classmethod
8687
def factory(cls, name, *args, **kwargs):
87-
types = {c.__name__: c for c in cls.__subclasses__()}
88+
types = {c.__name__: c for c in cls.__subclasses__()} # 忽略性能:P
8889
shape_class = types[name]
8990
return shape_class(*args, **kwargs)
9091
@@ -191,11 +192,58 @@ if __name__ == '__main__':
191192

192193
#### Decorator
193194

194-
装饰器,似乎不太需要举例了,Python自带的语法,可以用来做很多事情:
195+
装饰器,似乎不太需要解释,Python自带的语法,可以用来做很多事情,几个简单例子:
196+
197+
* 路由
198+
199+
```
200+
from flask import Flask
201+
app = Flask(__name__)
202+
203+
@app.route('/')
204+
def index():
205+
return 'Hello, World'
206+
207+
@app.route('/home')
208+
def home():
209+
return 'Welcome Home'
210+
```
195211

196212
* 权限控制
197-
* logwrap
198-
* 安全检查
213+
214+
```
215+
from django.contrib.auth.decorators import login_required
216+
217+
@login_required
218+
def my_view(request):
219+
...
220+
```
221+
222+
* 输入输出
223+
224+
```
225+
from functools import wraps
226+
227+
228+
def debug(f):
229+
@wraps(f)
230+
def debug_function(*args, **kwargs):
231+
print('call: ', f.__name__, args, kwargs)
232+
ret = f(*args, **kwargs)
233+
print('return: ', ret)
234+
return debug_function
235+
236+
237+
@debug
238+
def foo(a, b, c=None):
239+
print(a, b, c)
240+
return True
241+
242+
243+
if __name__ == '__main__':
244+
foo(1, 2, 3)
245+
```
246+
199247

200248

201249

0 commit comments

Comments
 (0)