上下文是什么?
- 带有with的代码块
- 上下文的好处是可以避免资源忘了释放
- 理论派可以去看看网上资料
- 下面的例子很直观
# -*- coding: utf-8 -*-
"""什么是上下文,看下下面的例子先"""
f = open('hello.txt', 'w')
try:
f.write('hello, world')
finally:
f.close()
with open('hello.txt', 'w') as f:
f.write('hello, world!')
通过类做一个上下文,来处理文件编辑
- 有一个实例方法
__enter__(self)
,用来返回上下文对象(上面例子里的f)
- 有一个实例方法
__exit__(self, exc_type, exc_val, exc_tb)
,用来关闭资源
-
__exit__
方法的参数exc_type, exc_val, exc_tb是发生异常时传入的异常类型、异常值、异常的trace_back。
# -*- coding: utf-8 -*-
"""自己实现一个处理文本的上下文处理器, 我们用来写个文件"""
class ManageFile(object):
def __init__(self, file_name, handle):
self.file_name = file_name
self.handle = handle
def __enter__(self):
self.file = open(self.file_name, self.handle)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with ManageFile('hello.txt', 'w') as f:
f.write('haha')
通过contextlib库来做一个上下文,来处理文件编辑
# -*- coding: utf-8 -*-
"""通过contextlib实现一个上下文处理器"""
from contextlib import contextmanager
@contextmanager
def manage_file(file_name, handle):
try:
f = open(file_name, handle)
yield f
finally:
f.close()
with manage_file('hello2.txt', 'w') as f:
f.write('hello2')
福利:用上下文来实现排版打印
# -*- coding: utf-8 -*-
"""利用上下文实现间隔打印"""
class Indenter(object):
def __init__(self):
self.level = 0
def __enter__(self):
self.level += 1
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.level -= 1
def print_(self, text):
print ' ' * self.level + text
with Indenter() as indent:
indent.print_('hi!')
with indent:
indent.print_('locke')
with indent:
indent.print_('cucumnber')
indent.print_('over')
网友评论