ITPub博客

首页 > 应用开发 > IT综合 > python with 用法

python with 用法

原创 IT综合 作者:G8bao7 时间:2015-10-26 14:09:31 0 删除 编辑


点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding=utf8

  3. import sys

  4. '''
  5. must implement method '__enter__' and '__exit__'. same as
  6. try:
  7.     __enter__
  8.     block
  9. finally:
  10.     __exit__
  11. '''
  12. class WithCls():
  13.     # execute before run block
  14.     # 可以不定义参数 *args
  15.     def __enter__(self, *args):
  16.         print("%s(%s) called " % (sys._getframe().f_code.co_name, args))
  17.         res = True
  18.         return res

  19.     # 当block发生 异常、错误、exit等情况时调用
  20.     # 必须定义 *args,接收异常等信息
  21.     def __exit__(self, *args):
  22.         print("%s(%s) called " % (sys._getframe().f_code.co_name,args))
  23.         # raise exception
  24.         res = False
  25.         # not raise exception
  26.         res = True
  27.         return res

  28. # t = __enter__, 可以不加t
  29. with WithCls() as t:
  30.     print("t is not the result of WithCls(), it is __enter__ returned")
  31.     # will call __exit__, and exit
  32.     raise NameError("Hi there")
  33.     print("Never here")

  34.     exit(0)



参考:
http://blog.csdn.net/shuimuniao/article/details/8206812


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26250550/viewspace-1816342/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-11-04

  • 博文量
    496
  • 访问量
    1258263