这个概念属于语言学科,指的是一段话的意义,要参考当前的场景,既上下文
在python中,上下文能够理解为是一个代码区间,一个范围 ,例如with open 打开的文件仅在这个上下文中有效python
with open('a.txt') as f: '代码块'
上代码编程
class Open: def __init__(self, name): self.name = name def __enter__(self): print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量') # return self def __exit__(self, exc_type, exc_val, exc_tb): print('with中代码块执行完毕时执行我啊') with Open('a.txt') as f: print('=====>执行代码块') # print(f,f.name)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
网络
上代码app
class Open: def __init__(self, name): self.name = name def __enter__(self): print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量') def __exit__(self, exc_type, exc_val, exc_tb): print('with中代码块执行完毕时执行我啊') print(exc_type) print(exc_val) print(exc_tb) try: with Open('a.txt') as f: print('=====>执行代码块') raise AttributeError('***着火啦,救火啊***') except Exception as e: print(e)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'>
\\\着火啦,救火啊\\\
<traceback object at 0x1065f1f88>
\\\着火啦,救火啊\\\
code
class Open: def __init__(self, name): self.name = name def __enter__(self): print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量') def __exit__(self, exc_type, exc_val, exc_tb): print('with中代码块执行完毕时执行我啊') print(exc_type) print(exc_val) print(exc_tb) return True with Open('a.txt') as f: print('=====>执行代码块') raise AttributeError('***着火啦,救火啊***') print('0' * 10) #------------------------------->会执行
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'>
***着火啦,救火啊***
<traceback object at 0x1062ab048>
0000000000
对象
列子一utf-8
class Open: def __init__(self, filepath, mode='r', encoding='utf-8'): self.filepath = filepath self.mode = mode self.encoding = encoding def __enter__(self): # print('enter') self.f = open(self.filepath, mode=self.mode, encoding=self.encoding) return self.f def __exit__(self, exc_type, exc_val, exc_tb): # print('exit') self.f.close() return True def __getattr__(self, item): return getattr(self.f, item) with Open('a.txt', 'w') as f: print(f) f.write('aaaaaa') f.wasdf #抛出异常,交给__exit__处理
<_io.TextIOWrapper name='a.txt' mode='w' encoding='utf-8'>'
列子二资源
class MyOpen(object): def __init__(self,path): self.path = path def __enter__(self): self.file = open(self.path) print("enter.....") return self def __exit__(self, exc_type, exc_val, exc_tb): print("exit...") # print(exc_type,exc_val,exc_tb) self.file.close() return True with MyOpen("a.txt") as m: # print(m) # print(m.file.read()) "123"+1 # m.file.read()
1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工做,无须手动干预get
2.在须要管理一些资源好比文件,网络链接和锁的编程环境中,能够在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处it