python中with用法讲解

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

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

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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")

执行结果:

?

1

2

3

4

5

6

7

8

9

10

11

12

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__方法,然后进入执行体,也就是:

?

1

2

3

print("hello python")

a = 1/0

print("hello end")

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

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

相关推荐

  1. pythonwith用法讲解

    2023-12-05 17:56:06       63 阅读
  2. Pythonwith语句以及它的用途

    2023-12-05 17:56:06       40 阅读
  3. 记录 | python with用法及原理

    2023-12-05 17:56:06       59 阅读
  4. 【android开发-20】androidnotification的用法讲解

    2023-12-05 17:56:06       48 阅读
  5. Pythonwith 关键字、tell() 和 seek() 方法

    2023-12-05 17:56:06       23 阅读
  6. pythonjson的用法(详细)

    2023-12-05 17:56:06       53 阅读
  7. pythonwith语句

    2023-12-05 17:56:06       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-05 17:56:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-05 17:56:06       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-05 17:56:06       82 阅读
  4. Python语言-面向对象

    2023-12-05 17:56:06       91 阅读

热门阅读

  1. uniapp vue3.2+ts h5端分环境打包

    2023-12-05 17:56:06       58 阅读
  2. 121. 买卖股票的最佳时机

    2023-12-05 17:56:06       56 阅读
  3. 编译原理Lab2-用bison完成语法分析器

    2023-12-05 17:56:06       49 阅读
  4. Hbuilderx+vue2+微信小程序 预览pdf

    2023-12-05 17:56:06       48 阅读
  5. 自己生成二维码

    2023-12-05 17:56:06       57 阅读
  6. oops-framework框架 之 音频管理(六)

    2023-12-05 17:56:06       61 阅读
  7. 【Redis】Redis缓存使用问题

    2023-12-05 17:56:06       73 阅读
  8. Whisper

    Whisper

    2023-12-05 17:56:06      48 阅读
  9. vue 路由跳转到其他页面指定位置(锚点)

    2023-12-05 17:56:06       52 阅读
  10. kafka kraft 集群搭建保姆级教学 包含几个踩坑点

    2023-12-05 17:56:06       57 阅读
  11. Spring Boot 统⼀数据返回格式

    2023-12-05 17:56:06       53 阅读
  12. IntelliJ IDEA详细完整安装教程

    2023-12-05 17:56:06       47 阅读