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