什么是Python与“声明用于? [英] What is the Python "with" statement used for?
问题描述
有一个很好的解释这里。 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屋!