十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
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电脑。