这篇文章主要介绍“Python上下文管理器实现方法有哪些”,在日常操作中,相信很多人在Python上下文管理器实现方法有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python上下文管理器实现方法有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
什么时候可以考虑上下文管理器
方法1(上下文管理器协议)
方法2(@contextmanager)
方法3(contextlib.closing())
当你的代码逻辑需要用到如下关键字时,可以考虑使用上下文管理器让你的代码更加优雅:
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。