python的with语法

python的with语法

   小樱     2021年3月10日 10:56     1220    

1.示例

不使用with语法打开文件

try:
    f =
open("data.txt" , 'r')
    data = f.read()
   
print(data)
except FileNotFoundError as e :
   
print(e)

 

使用with语法

with open("data.txt" , 'r')as f:
    data = f.read()
   
print(data)

上述均是打开文件并且读取其中内容。

 

2.with的原理

with语句是一个上下文管理协议。如果要使对象能够使用with语句,就需要在对象的类中声明__enter____exit__方法。

1)这里自己实现一个打开文件的类。

class my_open(object):
   
def __init__(self , filename , type):
       
self.filename = filename
       
self.type = type
   
def __enter__(self):
       
print("with语句开始执行")
       
self.handle = open(self.filename , self.type)
       
return self.handle
   
def __exit__(self, exc_type, exc_val, exc_tb):
       
print("with语句执行结束")
       
self.handle.close()
       
return True

with
my_open("data.txt" , 'r') as f:
    data = f.read()
   
print(data)

运行结果:

with语句开始执行

11111111

with语句执行结束

 

2)在__exit__的方法中有return True这个字段,下个程序将其删除之后,并且在调用的时候在with中抛出异常,下边的程序在执行的时候,如果碰到抛出的异常就会阻止程序的执行。

class my_open(object):
   
def __init__(self , filename , type):
       
self.filename = filename
       
self.type = type
       
# raise ImportError
   
def __enter__(self):
       
print("with语句开始执行")
       
self.handle = open(self.filename , self.type)
       
return self.handle
   
def __exit__(self, exc_type, exc_val, exc_tb):
       
print("with语句执行结束")
       
self.handle.close()
       
# return True
with my_open("data.txt" , 'r') as f:
    data = f.read()
   
print(data)
   
raise ImportError
print
("Program continues")

运行结果:

with语句开始执行

11111111

with语句执行结束

Traceback (most recent call last):

  File "D:/project/flaskpro/test/test_1.py", line 17, in <module>

    raise ImportError

ImportError

 

3)但是如果不将其删除的话,在遇到抛出异常的时候就不会阻止程序的运行。

class my_open(object):
   
def __init__(self , filename , type):
       
self.filename = filename
       
self.type = type
       
# raise ImportError
   
def __enter__(self):
       
print("with语句开始执行")
       
self.handle = open(self.filename , self.type)
       
return self.handle
   
def __exit__(self, exc_type, exc_val, exc_tb):
       
print("with语句执行结束")
       
self.handle.close()
       
return True
with
my_open("data.txt" , 'r') as f:
    data = f.read()
   
print(data)
   
raise ImportError
print
("Program continues")

运行结果:

with语句开始执行

11111111

with语句执行结束

Program continues


文章评论

0

其他文章