惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
GbyAI
GbyAI
S
SegmentFault 最新的问题
量子位
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
IT之家
IT之家
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
雷峰网
雷峰网

老董笔记

尚硅谷机构在哪?尚硅谷培训怎么样?靠谱吗-互联网IT百科 韩顺平介绍,传智讲师,开办泰牛,入尚硅谷等一系列-互联网IT百科 pandas多重索引标准样式(写入excel有空行)-互联网IT百科 cannot join with no overlapping index names-互联网IT百科 pandas多列变多行(即宽表变长表)melt和stack函数-互联网IT百科 pandas多行转多列(长表变宽表)pivot和unstack-互联网IT百科 Index contains duplicate entries, cannot reshape完美解决-互联网IT百科 single positional indexer is out-of-bounds-互联网IT百科 Can only compare identically-labeled Series objects-互联网IT百科 pandas transform用法详解(多个案例)-互联网IT百科 python四舍五入精确实现-互联网IT百科 pandas的groupby使用apply分组排序-互联网IT百科 index 0 is out of bounds for axis 0 with size 0-互联网IT百科 pandas分组过滤filter函数-互联网IT百科 联想Win10系统如何禁用触摸屏关闭触摸-互联网IT百科 groupby分组计算transform转换返回相同长度序列-互联网IT百科 brooks seo教程python教程,brooks seo教程网盘,布鲁seo资源-互联网IT百科 电脑右键文件夹一直转圈电卡死怎么回事-互联网IT百科 施琪嘉的心理成长课(荐)-互联网IT百科 百度SEO公司_SEO推广公司哪家好_SEO外包服务如何选-老董笔记 groupby后agg同1列用多个聚合函数、不同列用不同函数、自定义函数-互联网IT百科 pandas的groupby单列多列分组聚合运算-互联网IT百科 DataFrameGroupBy对象及分组个数、分组大小、组名索引、组数据详解-互联网IT百科 pandas中groupby之Grouper and axis must be same length-互联网IT百科 pandas中groupby的分组原理-互联网IT百科 pandas的groupby的使用详解大全-互联网IT百科 openpyxl单元格自动换行强制换行Alignment(wrapText=True)-互联网IT百科 python教程全套(可就业)-互联网IT百科 联想win10系统CPU显示100%,电脑呼呼响怎么回事-互联网IT百科 如何自制CPU,CPU原理是怎么样的?-互联网IT百科
什么是上下文管理器,基于类自定义上下文管理器-互联网IT百科
2021-11-18 · via 老董笔记

  在文件操作时经常用with as 语句,同时接触了上下文管理器的概念。其实上下文是context直译的说法,在程序中用来表示某段代码所处的前后环境,比如在文件中写入数据,写入之前要打开文件,写入之后要关闭文件。

  在python中,一个类只要实现了__enter__()和__exit__()这2个方法就代表实现了上下文管理协议。

  在python中,同时包含__enter__()和__exit__()方法的对象就是上下文管理器。

  实际使用上下文管理器离不开with语法,with语法格式如下:

  
with context_expression as var:
  # 一段代码块

  上述代码中context_expression代表上下文管理器,as var可以省略,但是往往会用到这个变量所以不省略。

  __enter__:进入with语法块之前调用,返回值会赋值给as后面的变量

  __exit__:退出with语法块后自动调用的方法,可以拿到with语句块内的异常详细信息

  我们自己写一个类来验证下

class TestWith:

    def __enter__(self):
        print('__enter__')
        return '...python66...'

    def __exit__(self, exc_type, exc_value, exc_tb):
        print('---- exc_type: %s' % exc_type)
        print('==== exc_value: %s' % exc_value)
        print('**** exc_tb: %s' % exc_tb)
        print('...end...')

with TestWith() as var:
  print(f'value:{var}')
__enter__
value:...python66...
---- exc_type: None
==== exc_value: None
**** exc_tb: None
...end...

  当with中执行的代码发生异常时,异常信息会被发送到 __exit__()方法的三个参数中:

  1)exc_type : 异常类型

  2)exc_val : 异常值

  3)exc_tb : 异常堆栈信息追踪

  我们在with语句块中写点能抛出异常的代码测试下

class TestWith:

    def __enter__(self):
        print('__enter__')
        return '...python66...'

    def __exit__(self, exc_type, exc_value, exc_tb):
        print('---- exc_type: %s' % exc_type)
        print('==== exc_value: %s' % exc_value)
        print('**** exc_tb: %s' % exc_tb)
        print('...end...')

with TestWith() as var:
  print(f'value:{var}')
  print(haha)
__enter__Traceback (most recent call last):

value:...python66...
---- exc_type: <class 'NameError'>
==== exc_value: name 'haha' is not defined
**** exc_tb: <traceback object at 0x0000000017C65F08>
...end...
  File "C:UsersAdministratorDesktop	est.py", line 73, in <module>
    print(haha)
NameError: name 'haha' is not defined

  如果__exit__()返回的是True,那么这个异常就被忽略。如果__exit__()返回的是True以外的任何东西,那么这个异常才被with语句抛出。

class TestWith:

    def __enter__(self):
        print('__enter__')
        return '...python66...'

    def __exit__(self, exc_type, exc_value, exc_tb):
        print('---- exc_type: %s' % exc_type)
        print('==== exc_value: %s' % exc_value)
        print('**** exc_tb: %s' % exc_tb)
        print('...end...')
        return True

with TestWith() as var:
  print(f'value:{var}')
  print(haha)
__enter__
value:...python66...
---- exc_type: 
==== exc_value: name 'haha' is not defined
**** exc_tb: <traceback object at 0x0000000017C79E88>
...end...

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会