Skip to content

Commit a9dff55

Browse files
committed
add python_context.py
1 parent fa82a31 commit a9dff55

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737
### python_magic_methods: Python进阶: 实例讲解Python中的魔法函数(Magic Methods)
3838

3939
### python_restful_api.py: 利用Python和Flask快速开发RESTful API
40+
41+
### python_context.py: With语句和上下文管理器ContextManager
4042
===================================================================================================
4143

4244
### 您可以fork该项目, 并在修改后提交Pull request

python_context.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
python_context.py by xianhu
5+
"""
6+
7+
import contextlib
8+
9+
10+
# 自定义打开文件操作
11+
class MyOpen(object):
12+
13+
def __init__(self, file_name):
14+
"""初始化方法"""
15+
self.file_name = file_name
16+
self.file_handler = None
17+
return
18+
19+
def __enter__(self):
20+
"""enter方法,返回file_handler"""
21+
print("enter:", self.file_name)
22+
self.file_handler = open(self.file_name, "r")
23+
return self.file_handler
24+
25+
def __exit__(self, exc_type, exc_val, exc_tb):
26+
"""exit方法,关闭文件并返回True"""
27+
print("exit:", exc_type, exc_val, exc_tb)
28+
if self.file_handler:
29+
self.file_handler.close()
30+
return True
31+
32+
# 使用实例
33+
with MyOpen("python_base.py") as file_in:
34+
for line in file_in:
35+
print(line)
36+
raise ZeroDivisionError
37+
# 代码块中主动引发一个除零异常,但整个程序不会引发异常
38+
39+
40+
# 内置库contextlib的使用
41+
@contextlib.contextmanager
42+
def open_func(file_name):
43+
# __enter__方法
44+
print("open file:", file_name, "in __enter__")
45+
file_handler = open(file_name, "r")
46+
47+
yield file_handler
48+
49+
# __exit__方法
50+
print("close file:", file_name, "in __exit__")
51+
file_handler.close()
52+
return
53+
54+
# 使用实例
55+
with open_func("python_base.py") as file_in:
56+
for line in file_in:
57+
print(line)
58+
break
59+
60+
61+
# 内置库contextlib的使用
62+
class MyOpen2(object):
63+
64+
def __init__(self, file_name):
65+
"""初始化方法"""
66+
self.file_handler = open(file_name, "r")
67+
return
68+
69+
def close(self):
70+
"""关闭文件,会被自动调用"""
71+
print("call close in MyOpen2")
72+
if self.file_handler:
73+
self.file_handler.close()
74+
return
75+
76+
# 使用实例
77+
with contextlib.closing(MyOpen2("python_base.py")) as file_in:
78+
pass

0 commit comments

Comments
 (0)