-
#!/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博客 ” ,链接:https://blog.itpub.net/26250550/viewspace-1816342/
,如需转载,请注明出处,否则将追究法律责任。