Python context Management protocol, which is the detailed use of with

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.