[python] with statement
An example presentation
1 import sys 2 class test: 3 def __enter__(self): 4 print("enter") 5 return 1 # return value is assigned to 't' 6 def __exit__(self,*args): 7 print("exit") 8 #return True # True: raise statement is never executed, thinking nothing happen 9 return False # False: raise statement will be executed. 10 with test() as t: 11 print("t is not the result of test(), it is __enter__ returned") 12 print("t is 1, yes, it is {0}".format(t)) 13 raise NameError("Hi there") 14 sys.exit() 15 print("Never here") 16 17 ##return True 18 ##>>> 19 ##enter 20 ##t is not the result of test(), it is __enter__ returned 21 ##t is 1, yes, it is 1 22 ##exit 23 ## 24 ##return False 25 ##>>> 26 ##enter 27 ##t is not the result of test(), it is __enter__ returned 28 ##t is 1, yes, it is 1 29 ##exit 30 ## 31 ##Traceback (most recent call last): 32 ## File "C:\Python27\EX\test.py", line 13, in <module> 33 ## raise NameError("Hi there") 34 ##NameError: Hi there
if one Class contains __enter__ and __exit__ method, like as below: "with" statement can be used.
1 class test(): 2 def __enter__(self): 3 print '__enter__' 4 return thing 5 def__exit__(self,*args): 6 print '__exit__, this is definitely executed' 7 return True#False/True is used for controlling the raise statement 8 with test() as thing: 9 print 'do something'
浙公网安备 33010602011771号