Python small white (no programming foundation, no computer basis) development of the Road auxiliary knowledge 1 with...as

Source: Internet
Author: User

This syntax is used instead of the traditional try...finally syntax.

With EXPRESSION [as VARIABLE] With-block

The basic idea is that the object with which the value is evaluated must have a __enter__ () method, a __exit__ () method.

Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS. The __exit__ () method of the previous return object is called when all code blocks following the with are executed.

[Python]
    1. File = open ("/tmp/foo.txt")
    2. Try
    3. data = File.read ()
    4. Finally
    5. File.close ()

Use with...as ... Replace the modified code with the following:

[Python]
    1. With open ("/tmp/foo.txt") as File:
    2. data = File.read ()
[Python]
  1. #!/usr/bin/env python
  2. # with_example01.py
  3. Class Sample:
  4. def __enter__ (self):
  5. print ( "in __enter__ ()")
  6. return "Foo"
  7. def __exit__ (self, type, value, trace):
  8. print ( "in __exit__ ()")
  9. Def get_sample ():
  10. return Sample ()
  11. With Get_sample () as Sample:
  12. Print ( "Sample:", sample)

Execution results are [Python]
    1. In __enter__ ()
    2. Sample:foo
    3. In __exit__ ()

1. The __enter__ () method is executed

2. The value returned by the __enter__ () method-This example is "Foo", assigned to the variable ' sample '

3. Execute code block, print variable "sample" with the value "Foo"

4. The __exit__ () method is called with the real power that it can handle exceptions. You may have noticed that the __exit__ method of the sample class has three parameters-Val, type, and trace. These parameters are quite useful in exception handling.

Python small white (no programming foundation, no computer basis) development of the Road auxiliary knowledge 1 with...as

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: info-contact@alibabacloud.com 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.