【python语法问题】特殊语句、语法结构0:with...as...

部署运行你感兴趣的模型镜像

首先理解什么是上下文管理器。

一种用于管理资源的对象。

通过实现 __enter__()__exit__() 方法来确保资源被正确地获取和释放,无论代码块中是否发生异常。

说白了就是有打开和关上的操作的一个东西。

案例:文件操作

with open("example.txt", "w") as file:
    file.write("Hello, World!")
  • open("example.txt", "w") 创建了一个文件对象,这个文件对象是一个上下文管理器。

  • __enter__() 方法被调用,打开文件并返回文件对象赋值给 file

  • with 代码块中,可以使用 file 变量来写入文件。

  • 当退出 with 代码块时,__exit__() 方法被调用,关闭文件。

案例:数据库连接管理

class DatabaseConnection:
    def __init__(self, db_name):
        self.db_name = db_name
        self.connection = None

    def __enter__(self):
        print(f"Connecting to database {self.db_name}...")
        # 模拟连接数据库
        self.connection = f"Connection to {self.db_name}"
        return self.connection  # 返回数据库连接对象

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Closing connection to database {self.db_name}...")
        # 模拟关闭数据库连接
        self.connection = None

# 使用 with as 语句管理数据库连接
with DatabaseConnection("my_database") as db_conn:
    print(f"Database connection: {db_conn}")
    # 在这里执行数据库操作

案例:线程池管理

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=24) as executor:
    # 提交任务到线程池
    future = executor.submit(lambda x: x * x, 2)
    print(future.result())  # Output: 4

with...as...是一种用于资源管理的语法结构。

代码示例:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • open("example.txt", "r") 返回一个文件对象
  • with 语句自动调用文件对象的 __enter__() 方法获取资源
  • 打开文件,返回文件对象赋值给 file
  • 在代码块内部对文件进行读取操作
  • 自动调用文件对象的 __exit__() 方法,关闭文件

with后面加上下文管理器(context manager),可以是类,也可以是具体对象。

代码示例:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=24) as executor:
    # 在这个代码块中,可以使用 executor 来提交任务
    future = executor.submit(lambda x: x * x, 2)
    print(future.result())  # Output: 4

上文中open()是一个具体对象实例,但此处ThreadPoolExecutor 是一个类。

当使用 with ThreadPoolExecutor(max_workers=24) as executor 时,ThreadPoolExecutor(max_workers=24) 创建了一个 ThreadPoolExecutor 类的实例,这个实例就是一个上下文管理器。

as 后面加一个变量名,用于接收上下文管理器的 __enter__() 方法返回的对象。

比如在前述open代码块中,可以通过 file 这个变量来读取文件内容。

再比如前述thread代码块中,可以通过executor来使用线程池管理器ThreadPoolExecutor的所有方法,比如executor.submit(函数名,参数)来执行多线程。

    您可能感兴趣的与本文相关的镜像

    Python3.10

    Python3.10

    Conda
    Python

    Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值