上下文是什么去件?
- 帶有with的代碼塊
- 上下文的好處是可以避免資源忘了釋放
- 理論派可以去看看網(wǎng)上資料
- 下面的例子很直觀
# -*- 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)
抑月,用來關(guān)閉資源
-
__exit__
方法的參數(shù)exc_type, exc_val, exc_tb是發(fā)生異常時傳入的異常類型、異常值舆蝴、異常的trace_back谦絮。
# -*- coding: utf-8 -*-
"""自己實現(xiàn)一個處理文本的上下文處理器题诵, 我們用來寫個文件"""
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庫來做一個上下文,來處理文件編輯
- 有興趣的可以看下源碼层皱,實際上肯定也是用上述那個類實現(xiàn)的啦性锭。。
# -*- coding: utf-8 -*-
"""通過contextlib實現(xiàn)一個上下文處理器"""
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')
福利:用上下文來實現(xiàn)排版打印
# -*- coding: utf-8 -*-
"""利用上下文實現(xiàn)間隔打印"""
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')
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者