python-->with-上下文管理器

1、概念

含有__enter__和__exit__方法的对象就是上下文管理器

2、语法

whith 上下文管理器:
    代码块

3、使用场景

只要创建/打开用完需要关闭时就可以用with实现,例如socket、文件读写、数据库连接等

4、第一种实现方式

__enter__() 方法返回资源对象,__exit__() 方法处理一些清除工作。

class WriteIn(object):
    def __init__(self, filePath, mode):
        self.filePath = filePath
        self.mode = mode

    def __enter__(self):
        self.f = open(self.filePath, self.mode)
        return self.f

    def __exit__(self, *args):
        self.f.close()

# 调用
with WriteIn("./jiekema.txt", "w") as f:
    f.write("我是杰克马")


通过@contextmanager装饰器实现上下文管理器

python提供的@contextmanager 装饰器,通过 yield 将函数分割成两部分,yield 之前的语句在 __enter__ 方法中执行,yield 之后的语句在 __exit__ 方法中执行。紧跟在 yield 后面的值是函数的返回值。

from contextlib import contextmanager

@contextmanager
def my_open(path, mode):
    f = open(path, mode)
    yield f
    f.close()


# 调用
with my_open('out.txt', 'w') as f:
    f.write("hello_world")

 

 

 

第二段代码等同于第一段代码

class WriteIn(object):
    def __init__(self, filePath, data):
        self.filePath = filePath
        self.data = data

    def writeIn(self):
        f = open(self.filePath, "w")
        try:
            f.write(self.data)
        except IOError:
            print("error")
        finally:
            f.close()

w = WriteIn("./a.txt", "哈哈")
w.writeIn()


class WriteIn(object):
    def __init__(self, filePath, data):
        self.filePath = filePath
        self.data = data

    def writeIn(self):
        with open(self.filePath, "w") as f:
            f.write(self.data)


w = WriteIn("./a.txt", "哈哈")
w.writeIn()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值