python with语句简介

本文介绍了Python中with语句的使用方法,包括直接使用with语句进行文件操作、自定义支持with语句的对象、利用contextlib模块定义with语句及适用于需要close操作的对象的with语句用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在python中读写操作资源,最后需要释放资源。可以使用try…finally结构实现资源的正确释放,python提供了一个with语句能更简便的实现释放资源。

1. python像文件的操作open等已经可以直接使用with语句
2. 可以自定义一个支持with语句对象
3. 使用contextlib也可以使用with语句对象
4. 针对需要close操作的对象with的使用

示例代码中有4种使用标注
# 自定义支持with语句的对象
class DummyRes:

    def __init__(self, tag):
        self.tag = tag

    def __enter__(self):
        print("Enter >>> {}".format(self.tag))
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        print("Exit <<< {}".format(self.tag))
        if exc_tb is None:
            print("Exit without Exception {}".format(self.tag))
            return False
        else:
            print("Exit with Exception {}".format(self.tag))
            return True

# 支持closing 上下文with语句对象
class Closing:

    def __init__(self, thing):
        self.thing = thing

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.thing.close()

class ClosingDemo:

    def __init__(self):
        self.acquire()

    def acquire(self):
        print("Acquire RES")

    def close(self):
        print("Close RES")

from contextlib import contextmanager

class ContextDemo:

    def __init__(self):
        print("Context Demo init")
        raise Exception
        print("Context Demo init")

    def print(self):
        print("Context Demo print 1")
        #raise Exception
        print("Context Demo print 2")

    def close(self):
        print("Context Demo close")

def context_demo():
    print("context demo in")
    raise Exception
    print("context demo out")

@contextmanager
def demo():
    print("Allocate Resoures")
    try:
        yield context_demo
    finally:
        print("raise exception")
    #yield "*** contextmanager demo ***"
    print("Free Resoures")

if __name__ == "__main__":

    # 1. 使用with语句 (自动关闭文件)
    with open("test.txt", "w") as f:
        f.write("write test")

    # 2. 自动定义with语句
    with DummyRes("test") as res:
        print("With body 1")
        raise Exception
        print("With body 2")

    # 3. 利用contextlib定义with语句
    with demo():
        print("exc demo")

    # 4. closing 上下文 (适合有close操作的情况)
    with Closing(ClosingDemo()):
        print("Use Resoures")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值