Skip to content

Commit 015168d

Browse files
committed
context
1 parent f965605 commit 015168d

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed

235.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,4 +253,8 @@ contextlib.contextmanager是一个装饰器,它作用于生成器函数(也
253253

254254
特别要提醒,被装饰的生成器函数只能产生一个值,否则就会抛出RuntimeError异常;如果有as子句,则所产生的值,会通过as子句赋给某个变量,就如同前面那样。
255255

256+
$ python 23504.py
257+
before yield.
258+
the word is: contextmanager demo.
259+
after yield.
256260

2code/23503.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#!/usr/bin/env python
2+
# coding=utf-8
3+
4+
import cairo
5+
from contextlib import contextmanager
6+
7+
@contextmanager
8+
def saved(cr):
9+
cr.save()
10+
try:
11+
yield cr
12+
finally:
13+
cr.restore()
14+
15+
def tree(angle):
16+
cr.move_to(0, 0)
17+
cr.translate(0, -65)
18+
cr.line_to(0, 0)
19+
cr.stroke()
20+
cr.scale(0.72, 0.72)
21+
if angle > 0.72:
22+
for a in [-angle, angle]:
23+
with saved(cr):
24+
cr.rotate(a)
25+
tree(angle * 0.75)
26+
27+
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 280, 204)
28+
cr = cairo.Context(surf)
29+
cr.translate(140, 203)
30+
cr.set_line_width(5)
31+
tree(0.75)
32+
surf.write_to_png('fractal-tree.png')

2code/23504.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python
2+
# coding=utf-8
3+
4+
from contextlib import contextmanager
5+
6+
@contextmanager
7+
def demo():
8+
print "before yield."
9+
yield "contextmanager demo."
10+
print "after yield."
11+
12+
with demo() as dd:
13+
print "the word is: %s" % dd
14+

2code/fractal-tree.png

1.34 KB
Loading

0 commit comments

Comments
 (0)