Just looked at the context Manager blog of the Vamei great God, understood as follows:
In fact, I often use the context manager, especially when opening files, if you are lazy, do not want to manually hit the F.close (), using the context manager OK pull.
The context manager is the with * * as:
For example, when you open a file,
The context manager invokes the __enter__ method of fi when it executes, and then calls the __exit__ method of FI, which completes the creation and closing of the file object.
Let's look at what the magic function of fi is:
fi = open (' 1 ', ' W ') >>> dir (FI) [' __class__ ', ' __delattr__ ', ' __doc__ ', ' __enter__ ', ' __exit__ ', ' __format__ ', ' _ _getattribute__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr ' __ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' close ', ' Closed ', ' encoding ', ' errors ', ' Fileno ', ' flush ', ' isatty ', ' Mode ', ' name ', ' newlines ', ' next ', ' read ', ' Readinto ', ' readline ', ' readlines ', ' seek ', ' softspace ', ' Tell ', ' truncate ', ' Write ', ' writelines ', ' xreadlines ']
Obviously, test the __enter__ and __exit__ methods:
>>> fi = open (' Test.txt ', ' R ') >>> fi.__enter__ () <open file ' test.txt ', mode ' R ' at 0X107225780>&G T;>> fi.__exit__ () >>> fi.closedtrue
Obviously, the __ENTER__ function opens the file, and the __exit__ function closes the file.
With this principle, we can write our own objects with __enter__ and __exit__ functions, so that we can use context management for these objects.
Principle of context Management:
#with * * AS:OBJECT.__ENTER__ () Try: block# may throw an exception finally: object.__exit__ ()
Context Manager in Python