python with 用法

G8bao7發表於2015-10-26


點選(此處)摺疊或開啟

  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部落格 ” ,連結:http://blog.itpub.net/26250550/viewspace-1816342/,如需轉載,請註明出處,否則將追究法律責任。

相關文章