今天小编给大家分享一下Python上下文管理器如何实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
当你的代码逻辑需要用到如下关键字时,可以考虑使用上下文管理器让你的代码更加优雅:
try:
...
finally:
...
接下来介绍实现上下文管理器的三种方法。
总所周知,open()是默认支持上下文管理器的。所以打开一个txt文件,并向里面写入内容,再关闭这个文件的代码可以这样写:
with open("1.txt", "w") as file:
file.write("this is a demo")
这是等同于:
file = None
try:
file = open("1.txt", "w")
file.write("this is a demo")
finally:
file.close()
要在Python中实现with语句的使用,就需要借助上下文管理器协议。也就是需要实现__enter__和__exit__两个魔法方法。
class OpenMyFile(object):
def __init__(self, path):
self.path = path
def __enter__(self):
print("opening the txt")
self.f = open(self.path, "w")
return self
def __exit__(self, *args, **kwargs):
print("closing the txt")
self.f.close()
def write(self, string):
print("writing...")
self.f.write(string)
with OpenMyFile("2.txt") as file:
file.write("this is a demo2")
# 输出:
opening the txt
writing...
closing the txt
同时能够看到本地生成了2.txt文件。需要注意的是,__enter__得return实例对象,不然会报异常:AttributeError: "NoneType" object has no attribute "write"
这是因为Python中的函数默认返回None。
利用contextlib中的contextmanager装饰器。
from contextlib import contextmanager
@contextmanager
def open_my_file(path):
print("opening the txt")
f = open("3.txt", "w")
yield f
print("closing the txt")
f.close()
with open_my_file("3.txt") as file:
file.write("this is demo3")
# 输出:
opening the txt
closing the txt
在@contextmanager装饰的函数中,需要用yield隔开两个逻辑语句。这里yield出来的对象会被as后面的变量接收。
利用contextlib中的closing()方法。
from contextlib import closing
class OpenMyFile(object):
def __init__(self, path):
print("opening the txt")
self.f = open(path, "w")
def write(self, string):
self.f.write(string)
def close(self):
print("closing the txt")
self.f.close()
with closing(OpenMyFile("4.txt")) as file:
file.write("this is demo4")
# 输出:
opening the txt
closing the txt
与方法1不同。经过closing()方法包装过后,在with语句结束时,会强制调用对象的close()方法。所以使用方法3时,需要定义的方法不是__exit__()而是close()。
以上就是“Python上下文管理器如何实现”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。