• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python中with用法讲解

python 搞代码 4年前 (2022-01-07) 21次浏览 已收录 0个评论

在本篇文章里小编给大家整理的是关于python中with用法讲解内容,有需要的朋友们可以参考下。

我们都知道打开文件有两种方法:

  • f = open()
  • with open() as f:

这两种方法的区别就是第一种方法需要我们自己关闭文件;f.close(),而第二种方法不需要我们自己关闭文件,无论是否出现异常,with都会自动帮助我们关闭文件,这是为什么呢?

我们先自定义一个类,用with来打开它:

 class Foo(): def __enter__(self): print("enter called") def __exit__(self, exc_type, exc_val, exc_tb): print("exit called") print("exc_type :%s"%exc_type) print("exc_val :%s"%exc_val) print("exc_tb :%s"%exc_tb) with Foo() as foo: print("hello python") a = 1/0 print("hello end")

执行结果:

 enter called Traceback (most recent call last): hello python exit called exc_type : exc_val :division by zero Fil<p style="color:transparent">来源gao!daima.com搞$代!码网</p>e "F:/workspaces/python_workspaces/flask_study/with.py", line 25, in  a = 1/0 exc_tb : ZeroDivisionError: division by zero Process finished with exit code 1

我们看到,执行结果的输入顺序,分析如下:

当我们with Foo() as foo:时,此时会执行__enter__方法,然后进入执行体,也就是:

 print("hello python") a = 1/0 print("hello end")

语句,但是在a=1/0出现了异常,with将会中止,此时就执行__exit__方法,就算不出现异常,当执行体被执行完毕之后,__exit__方法仍然被执行一次。

我们回到with open(“file”)as f: 不用关闭文件的原因就是在__exit__方法中,存在关闭文件的操作,所以不用我们手工关闭文件,with已将为我们做好了这个操作,这就可以理解了。

以上就是小编整理的相关内容,如果大家有任何补充可以联系gaodaima搞代码网小编。

以上就是python中with用法讲解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中with用法讲解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址