python with 用法
點選(此處)摺疊或開啟
-
#!/usr/bin/env python
-
#coding=utf8
-
-
import sys
-
-
'''
-
must implement method '__enter__' and '__exit__'. same as
-
try:
-
__enter__
-
block
-
finally:
-
__exit__
-
'''
-
class WithCls():
-
# execute before run block
- # 可以不定義引數 *args
-
def __enter__(self, *args):
-
print("%s(%s) called " % (sys._getframe().f_code.co_name, args))
-
res = True
-
return res
-
-
# 當block發生 異常、錯誤、exit等情況時呼叫
- # 必須定義 *args,接收異常等資訊
-
def __exit__(self, *args):
-
print("%s(%s) called " % (sys._getframe().f_code.co_name,args))
-
# raise exception
-
res = False
-
# not raise exception
-
res = True
-
return res
-
-
# t = __enter__, 可以不加t
-
with WithCls() as t:
-
print("t is not the result of WithCls(), it is __enter__ returned")
-
# will call __exit__, and exit
-
raise NameError("Hi there")
-
print("Never here")
-
- exit(0)
參考:
http://blog.csdn.net/shuimuniao/article/details/8206812
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26250550/viewspace-1816342/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- python print 用法Python
- python xpath用法Python
- Python Dict用法Python
- Python yield 用法Python
- Python字典dict用法Python
- python pil resize 用法Python
- python-lambda用法Python
- 【python】list 的用法Python
- python, del[] 用法, 笨方法學pythonPython
- python-random的用法Pythonrandom
- python中return的用法Python
- Python range() 函式用法Python函式
- Python排序函式用法Python排序函式
- python中的eval用法Python
- Python下劃線用法Python
- Python self用法詳解Python
- python BeautifulSoup用法介紹Python
- Python re模組, xpath 用法Python
- Python中set的用法Python
- Python語言assert用法Python
- Python with 語句的用法Python
- Python中下劃線用法Python
- python 中 pipenv 用法筆記Python筆記
- Python中return self的用法Python
- python ChainMap的突變用法PythonAI
- python的partial()用法說明Python
- Python迴圈結構用法Python
- python引數解析argparse用法Python
- Python中Collections.counter用法Python
- 【Python】*args 和 **kwargs的用法Python
- Python模板庫Mako的用法Python
- Python 中 Requests 庫的用法Python
- Python 中filter函式用法PythonFilter函式
- 【python】sys.argv[] 的用法Python
- python之函式用法divmodPython函式
- Python推導式 - 最全用法Python
- Python中operator 模組的用法Python
- Python中itertools 模組的用法Python