好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解有关Python上下文管理器和with块

这篇文章主要为大家详细介绍了Python上下文管理器和with块的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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块的详细内容...

  阅读:35次