Python的上下文管理器with

版权声明:本文由洛北辰南原创,转载请注明原创地址,谢谢。 https://blog.csdn.net/qq_18941713/article/details/84878994

Python保留了with,作为上下文管理器使用,代替了传统的try…catch…finally,作为处理任务异常终止的一种手段。就比如TensorFlow中的会话
不使用with,却在手动关闭会话前,程序异常终止,那么该会话占用的资源就无法释放,造成资源泄露。
而使用with,交由实体类的__exit__方法对资源进行释放,就能解决这种问题。

创建一个类,来演示with的作用。

# -*- coding: utf-8 -*-
# @Time    : 2019/3/5 17:14
# @Author  : Chord
class Example:
    # 定义函数初始化方法
    def __init__(self):
        print("in __init__")
	# 定义函数入口方法
    def __enter__(self):
        print("in __enter__")
        return "be created"
    # 定义函数退出方法
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("in __exit__")

def NewExample():
    return Example()

if __name__ == "__main__":
    with NewExample() as example:
        print("Now is "+example)
# 执行完毕会自动调用 __exit__方法
# 在代码正常运行的情况下
output:
in __init__
in __enter__
Now is be created
in __exit__
# 在代码异常终止的情况下
# 为了满足条件,让变量调用一个不存在的方法
class Example:
    # 定义函数初始化方法
    def __init__(self):
        print("in __init__")
	# 定义函数入口方法
    def __enter__(self):
        print("in __enter__")
        return "be created"
    # 定义函数退出方法
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("in __exit__")

def NewExample():
    return Example()

if __name__ == "__main__":
    with NewExample() as example:
		example.hello()
		print("Now is "+example)
		
output:
# 在调用这个不存在的方法之前,with并没有结束。
# 程序异常终止,但是__exit__方法依旧是执行了
# 所以使用上下文管理器with,可以在程序异常终止时,释放资源。
in __init__
in __enter__
in __exit__
Traceback (most recent call last):
  File "with.py", line 21, in <module>
    example.hello()
AttributeError: 'str' object has no attribute 'hello'

猜你喜欢

转载自blog.csdn.net/qq_18941713/article/details/84878994