First, with obj as F:
#代码块 ...
Second, the implementation process:
1.with obj---> Trigger obj.__enter__ (), need to write __enter__ (self) in obj, write return value inside it, return to as F
2.with obj as f equals f = obj.__enter__ ()
3. Execute the program in the With code block
4. When normal execution occurs, the __exit__ () method in obj is executed sequentially, Exc_type, Exc_val, and EXC_TB values are none.
When there is an exception, the __exit__ () method
A. Return false when False, throws a system exception.
B. Return True when returning false, swallow the system exception and customize the exception information yourself.
Third, its role: automatically clean up/release the resources in the code block, no need to consider these issues
classFoo:def __init__(SELF,AA): Self.aa=AAdef __enter__(self):Print('Run Enter') return Selfdef __exit__(self, exc_type, Exc_val, EXC_TB):Print('Run Exit') Print(Exc_type)#exception classes such as: Nameerror Print(Exc_val)#exception values such as: Name ' MyName ' is not defined Print(EXC_TB)#tracking information such as: Traceback (most recent): XXXX returnTrueWith Foo (11) as cc:Print(CC.AA)Print(CC.FF)Print('ssss')
Common Exception components
Traceback (most recent):(tracking information started)
File "d:/workspace/purepython3/exception. Py", line 1, <module>
MyName (end of tracking information)
Nameerror (Exception Class): Name ' myname ' is not defined (exception value)
Python context Management protocol, which is the detailed use of with