with context management

An example of a

First look at a piece of code:

class Foo(object):

    def __init__(self):

        print('实例化一个对象')

    def __enter__(self):

        print('进入')

    def __exit__(self, exc_type, exc_val, exc_tb):

        print('退出')



obj = Foo()

with obj:
    print('正在执行')

Results of the above code:

实例化一个对象
进入
正在执行
退出

Conclusion 1

We know that instantiate Foo, get the object obj, performs Foo's __init__ method, which is printed the first sentence;

According to the program execution from top to bottom, you should print "Progress" instead of asking first before it will print the entry, exit it after printing it?

 Because when we define Foo, defined __enter__ and __exit__ method, then we instantiate the object obj is a context manager,

** __enter__ i.e. containing objects and methods is __exit__ context manager. **

with 上下文管理器:
     语句体

Before encounter with a context manager, will execute the statement in the body, perform __enter__ method context manager, and then execute the statement body after body after executing the statement, the last execution method __exit__

 

This is the reason why there is the case at the beginning of the article.

Examples of the dicarboxylic

Look at this code:

class Foo(object):

    def __init__(self):
        print('实例化一个对象')

    def __enter__(self):
        print('进入')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')

     # return True

obj = Foo()

with obj:
    raise ImportError
    print('正在执行')

The results are as follows:

 The code above the line that we commented uncommented, the following results

 

 We find that, although we deliberately throw an error, under normal circumstances, to perform local error will not be executed, while __exit__ is performed after seeing the body executing the sentence in the body, but still performed __exit_ _ method; when we give a return value in __exit__ Ture, it will ignore the error.

 ```

Conclusion 2

All we can find

with a similar statement

  try :

  except:

  finally:

Functionality: But with statements more concise. And safer. Less code.

   When an exception occurs, if the Exit (default return value is not written, that is False) returns False, it will re-thrown, let statement outside with logic to handle exceptions, and this is common practice; if it returns True, then ignored abnormalities, no abnormal processing

Examples of three

class Foo(object):

    def __init__(self):
        print('实例化一个对象')

    def __enter__(self):
        print('进入')
        # return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')

with Foo() as obj:
    print(obj,type(obj))
    print('正在执行')

The code above the line that we commented uncommented, the following results

in conclusion

Call context manager enter when the method; if used as clause, then enter () method returns the value assigned to the target as clause

with 上下文管理器  as  target:

    代码语句体

with后面必须跟一个上下文管理器,如果使用了as,则是把上下文管理器的 enter() 方法的返回值赋值给 target,target 可以是单个变量,或者由“()”括起来的元组(不能是仅仅由“,”分隔的变量列表,必须加“()”)

例子四

我们经常会看到这样的代码:

with open("/tmp/foo.txt") as file:
    data = file.read()

 结论

这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件句柄。如果使用传统的 try/finally 范式,则要使用类似如下代码:

somefile = open(r'somefileName')
try:
    for line in somefile:
        print line
        # ...more code
finally:
    somefile.close()

比较起来,使用 with 语句可以减少编码量。已经加入对上下文管理协议支持的还有模块 threading、decimal 等。

补充

with只能配合上下文管理器使用,常见的上下文管理器有

file

decimal.Context

thread.LockType

threading.Lock

threading.RLock

threading.Condition

threading.Semaphore

threading.BoundedSemaphore

 

Guess you like

Origin www.cnblogs.com/zhaogang0104/p/11906715.html