如何在python中使用with

发布时间:2021-03-31 17:14:48 作者:Leah
来源:亿速云 阅读:111

本篇文章给大家分享的是有关如何在python中使用with,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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

这两种方法的区别就是第一种方法需要我们自己关闭文件;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 :<class 'ZeroDivisionError'>
exc_val :division by zero
 File "F:/workspaces/python_workspaces/flask_study/with.py", line 25, in <module>
  a = 1/0
exc_tb :<traceback object at 0x0000023C4EDBB9C8>
ZeroDivisionError: division by zero

Process finished with exit code 1

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

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

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

以上就是如何在python中使用with,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 如如何使用journalctl命令?
  2. bootstrap下拉列表如设置

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python with

上一篇:怎么在java中使用运算符

下一篇:continue语句如何在Python中使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》