ITPub博客

首页 > IT职业 > IT生活 > python with语句的工作原理

python with语句的工作原理

IT生活 作者:keehoo 时间:2021-09-11 09:57:40 0 删除 编辑

1、说明

(1)上下文管理器对象必须有内置操作符__enter__和__exit__方法。

(2)在with句子中返回对象管理器并分配变量时,将召回__enter__方法。

(3)执行嵌套句,即上述相关代码。

(4)如果出现异常信息,将回调__exit__的方法,同时携带type,value,traceback三个参数(通过sys.exc_info获得)

(5)在正常执行完成后,还召回__exit__的方法。

2、实例

# exception.pyclass WithContextObject:
    def message(self,args):
        print(args)            def __enter__(self):
        print("execute enter method ..")                return self            def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            print("execute normally...")                else:
            print("raise exception ...")                        return Falsedef test_with():
    with WithContextObject() as context:
        context.message("take message")         if __name__ == '__main__':
    test_with()>>> python exception.py

以上就是python with语句的工作原理,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4357/viewspace-2830345/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    631