Python with AS

Source: Internet
Author: User

It is interesting to use the lock in multipressing when using the process today, using a with lock once.

The object of the processing idea of the with in Python four with the value to be evaluated must have a __enter__ () method, a __exit__ () method.

The __enter__ () method of the returned object is called after the statement immediately following the with is evaluated, and the return value of the method returns the value to the variable following the AS.

The __exit__ () method of the previous return object is called when all the code blocks following the with are executed.

# class sample:#     def __enter__ (self): #         print ("in __enter ()") #         return ' Foo ' #     def __exit__ (self, exc_ Type, Exc_val, EXC_TB): #         print (' in __exit__ () ') # # Def get_sample (): #     return to sample () # with Get_sample () as sample:#     Print (' Sample: ', sample)
In __enter__ () Sample:fooin __exit__ ()

The __enter__ () method is executed

__enter__ () method return value-in this case ' Foo ', assign to variable ' sample '
Execute code block, print variable ' sample ' with value ' Foo '

The __exit__ method is called

The __exit__ method with the sample class has three parameters-exc_type, Exc_val, EXC_TB,

# class sample:#     def __enter__ (self): #         return self#     def __exit__ (self, exc_type, Exc_val, EXC_TB): #         Print (' type: ', exc_type) #         print (' type: ', exc_val) #         print (' type: ', EXC_TB) #     def do_something (self): #         bar = 1/0#         return bar + 10# with Sample () as sample:#     sample.do_something ()

With will automatically call her class, then execute __enter__, execute the WITH method and the With method, and then execute the __EXIT__ function, which will automatically close, recycle resources and so on.

  

Python 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.