Context:
Start information
|
Intermediate output Information
|
End Message
Contextual Environment 1:
#!/usr/bin/python# -*- coding: utf-8 -*-class query (object): Def __init__ (self, name): self.name = name def __enter__ (self): print (' Begin ' ) return self def __exit__ ( Self, exc_type, exc_value, traceback): if Exc_type: print (' Error ') else: print (' End ') def query (self): print (' query info about %s ... ' % self.name) with query(' Bob ') as q: q.query () query ( ' Bob '). Query ()
run Result:
Beginquery info about Bob ... Endquery info about Bob ...
Context 2: @contextmanager
From contextlib import contextmanagerclass query (object): def __init__ (Self, name): self.name = name def query (self): print (' Query info about %s ' % self.name) @contextmanagerdef create_query (name): print (' Begin ') q = query (name) yield q print (' End ') with create_query (' Bob ') as q: q.query ()
Operation Result:
Beginquery info about Bob ... End
Context 3: @contextmanager simplify again
From contextlib import contextmanager@contextmanagerdef tag (name): Print ("<%s>"% name) yield print ("</% S> "% name" with tag ("H1"): Print ("Hello") Print ("World")
The result of the above code execution is:
No context: @closing use closing () to turn the object into a context object, for example, using Urlopen () with a with statement:
from contextlib import closingfrom urllib.request import urlopenwith Closing (Urlopen (' https://www.baidu.com ')) as page: for line in page: print (line)
B '
Don't know how to verify the closing
from contextlib import contextmanager@contextmanagerdef closing (thing): try: yield thing finally: thing.close ()
The result of the above code execution is:
Python Decorator: Contextlib