标签:with 工作 erro ace pytho 操作文件 __init__ pre 网络连接
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中代码块执行完毕时执行我啊
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,11)
print(exc_val,22)
print(exc_tb,33)
try:
with Open('a.txt') as f:
print('=====>执行代码块')
raise AttributeError('***着火啦,救火啊***,11')
except Exception as e:
print(e)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'> 11
***着火啦,救火啊***,11 22
<traceback object at 0x0BBB3BE8> 33
***着火啦,救火啊***,11
异常都会被执行
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, 1)
print(exc_val, 2)
print(exc_tb, 3)
return True
with Open('a.txt') as f:
print('=====>执行代码块')
raise AttributeError('***着火啦,救火啊***')
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'> 1
***着火啦,救火啊*** 2
<traceback object at 0x0BD63BE8> 3
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()
print(exc_type, 1)
print(exc_val, 2)
print(exc_tb, 3)
# 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 'AttributeError'> 1
'_io.TextIOWrapper' object has no attribute 'wasdf' 2
<traceback object at 0x0C443BE8> 3
实现文件上下文管理(\_\_enter\_\_和\_\_exit\_\_)
标签:with 工作 erro ace pytho 操作文件 __init__ pre 网络连接
原文地址:https://www.cnblogs.com/randysun/p/12253031.html