栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python--with语句、上下文管理器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python--with语句、上下文管理器

with语句(可以自动关闭资源 可以不用手动关闭)

print(type(open('a.txt','r')))
with open('a.txt','r') as file: #取别名
    print(file.read())

#open('a.txt','r')为上下文表达式,它的对象是上下文管理器

with语句可以自动管理上下文资源

with 上下文表达式 as 别名

 


上下文管理器

#MyContentMgr实现了特殊方法 __enter__和__exit__,所以称该类对象遵守了上下文管理协议
# 该类对象的实例对象 称为上下文管理器
class MyContentMgr(object):#上下文管理器
    def __enter__(self):
        print('enter方法被调用了')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit方法被调用了")
    #实例
    def show(self):
        print('show方法被执行了')

with MyContentMgr() as file:
    file.show()

出错了 也会退出


拷贝用上下文管理器实现

with open('a.png','rb') as file_scr: #取别名
    with open('c.png','wb') as file_tar:
        file_tar.write(file_scr.read())

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/965929.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号