Python with usage instance

Source: Internet
Author: User
In Python, with can significantly improve code-friendliness, such as:
Copy CodeThe code is as follows:


With open (' a.txt ') as F:
Print F.readlines ()


For our own class can also use with, as long as the class to add two function __enter__, __exit__ can:
Copy CodeThe code is as follows:


>>> class A:
def __enter__ (self):
print ' in Enter '
def __exit__ (self, e_t, E_v, T_b):
print ' in exit '

>>> with a () as a:
print ' in with '

In Enter
In with
In exit


In addition, there is a module contextlib in the Python library, so that you do not have to construct a class containing __enter__, __exit__ can use with:
Copy CodeThe code is as follows:


>>> from Contextlib import ContextManager
>>> from __future__ import with_statement
>>> @contextmanager
... def context ():
... print ' entering the zone '
... try:
... yield
... except Exception, E:
... print ' with ' Error%s '%e
... raise E
.. else:
... print ' with no error '
...
>>> with context ():
The. print '----In the context call------'
...
Entering the Zone
----in context call------
With no error


The most used is this contextmanager, and another closing is not very useful
Copy CodeThe code is as follows:


From Contextlib import closing
Import Urllib

With closing (Urllib.urlopen (' http://www.python.org ')) as page:
For line in page:
Print Line
  • 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.