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

with

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

with

with是个很好玩的东西,其本质是上下文管理。再详细点,就是给当前操作添加一个前置操作和后置操作。

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

对于一个对象,在这里,前置操作:def enter(self) 后置操作:exit(self, type, value, trace)

#!/usr/bin/env python
#with_example01.py
class Sample:
    def __enter__(self):
        print "In __enter__()"
        return "Foo"
    def __exit__(self, type, value, trace):
        print "In __exit__()"
def get_sample():
    return Sample()
with get_sample() as sample:
    print "sample:", sample

关键是后置操作这里,还有3个参数,通过这个,可对错误进行一系列处理。

目前常用的场景

1,读取文件

2,数据库事务

with transaction.atomic():

3,可以自己封装一个类,比如之前笔者写过一个限流加统计的程序,需要把执行内容放在笔者before与after方法里面,如果引用with的设计,代码则优雅太多。

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

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

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