什么是Python与“声明用于? [英] What is the Python "with" statement used for?

查看:148
本文介绍了什么是Python与“声明用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解python中的with语句。我到处都在谈论打开和关闭一个文件,并且是为了替换try-finally块。有人可以发布一些其他的例子。我只是尝试烧瓶,并有其中的陈述嘉豪。

解决方案

有一个很好的解释这里。 with语句基本上在关联的对象上调用两个特殊的方法。 __enter__和__exit__方法。 enter方法返回与with语句关联的变量。而__exit__方法在语句执行后处理任何清理(例如关闭文件指针)之后被调用。


I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someone post some other examples too. I am just trying out flask and there are with statements galore in it. Definitely request someone to provide some clarity on it.

解决方案

There's a very nice explanation here. Basically, the with statement calls two special methods on the associated object. The __enter__ and __exit__ methods. The enter method returns the variable associated with the "with" statement. While the __exit__ method is called after the statement executes to handle any cleanup (such as closing a file pointer).

这篇关于什么是Python与“声明用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆