Python中的with关键字

with关键字是干嘛用的?
with语句用于对try except finally 等的优化,让代码更加美观,
例如常用的读取文件的操作,用try except finally 实现:

try:
    fo=open( 'context.txt','r',encoding='utf8' )
    fo.read()
except:
    pass
finally:
    fo.close()

是不是显得有点拖泥带水了?不整洁不美观。
咱们用with关键字达到与其相同的功能:

with open( 'context.txt','r',encoding='utf8' ) as fo:
    fo.read()

这条语句就好简洁很多,当with里面的语句产生异常的话,也会正常关闭文件,可能因为Python内部的规则吧–

with关键字的使用:
with关键字,它实现了两个特殊的方法:enter() exit()
只要是with关键字修饰的函数必定都会有这两个方法

with 关键字的使用:

class Myhello:
    def __init__(self):
        print( "初始化" )
    def __enter__(self):
        print( "enter" )
    def __exit__(self,exceptionType,exceptionVal,trace):
        print("exit")
    

with Myhello():           
    print("你好")

在这里插入图片描述

不难看出:在执行Myhello()时,先对其初始化,然后再执行了它的 enter()函数,然后执行了with关键字里面的代码,执行完了之后会再执行__exit__()函数。
这好像和前面说的装饰器有点类似的地方,在不修改源码的情况下对其新增功能(个人见解)

感谢您的阅读,谢谢!

猜你喜欢

转载自blog.csdn.net/qq_39022311/article/details/83627798