with open('mirror.py') as fp:
... class A:
def __init__(self, name):
self.name = name
def __enter__(self):
print('enter')
return self.name
def __exit__(self, exc_type, exc_val, exc_tb):
print('gone')
with A('xiaozhe') as dt:
print(dt) import contextlib
@contextlib.contextmanager
def test(name):
print('start')
yield name
print('end')
with test('zhexiao123') as dt:
print(dt)
print('doing something') import contextlib
@contextlib.contextmanager
def test(name):
print('start')
try:
yield name
except:
raise ValueError('error')
finally:
print('end')
with test('zhexiao123') as dt:
print(dt)
print('doing something') 以上就是详解有关Python上下文管理器和with块的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于详解有关Python上下文管理器和with块的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did84460