Python with usage instance, pythonwith instance
In python, with can significantly improve code friendliness, such:
Copy codeThe Code is as follows:
With open('a.txt ') as f:
Print f. readlines ()
We can also use with for our own classes. Just add two functions _ enter __, _ exit _ to this class:
Copy codeThe Code is as follows:
>>> Class:
Def _ enter _ (self ):
Print 'in enter'
Def _ exit _ (self, e_t, e_v, t_ B ):
Print 'in exit'
>>> With A () as:
Print 'in'
In enter
In
In exit
In addition, the python Library also has a contextlib module, so that you do not need to construct a class containing _ enter __, _ exit _ to use:
Copy codeThe Code is as follows:
>>> From contextlib import contextmanager
>>> From _ future _ import with_statement
>>> @ Contextmanager
... Def context ():
... Print 'entering the zone'
... Try:
... Yield
... Failed t Exception, e:
... Print 'with an error % s' % e
... Raise e
... Else:
... Print 'with no error'
...
>>> With context ():
... Print '---- in context call ------'
...
Entering the zone
---- In context call ------
With no error
The most commonly used contextmanager, and another closing function is of little use.
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