### `__enter__`魔術(shù)方法:
使用`with`語句的時(shí)候,會調(diào)用這個(gè)魔術(shù)方法,這個(gè)方法的返回值可以作為`as xx`的值。
示例:
```python
with FileOpener('xxx.txt','w') as fp:
? ? pass
```
### `__exit__(self,exc_type,exc_val,exc_tb)`魔術(shù)方法:
1. 執(zhí)行完這個(gè)`with`語句中的代碼塊或者是這個(gè)代碼塊中的代碼發(fā)生了異常,就會執(zhí)行這個(gè)方法??梢栽谶@個(gè)方法中做一些清理工作。比如關(guān)閉文件等。
2. 如果在`with`語句中發(fā)生了異常,那么`exc_type`和`exc_val`將會存儲這個(gè)異常的信息,如果沒有任何異常,那么他們的值為`None`。
3. 如果在`with`語句中發(fā)生了異常,那么會執(zhí)行`__exit__`方法,但是如果你不想讓這個(gè)異常拋出`with`代碼塊,那么你可以返回`True`,就不會把異常拋出到外面了。
#encoding: utf-8
class FileOpener(object):
? ? def __init__(self,filename,mode):
? ? ? ? self.filename = filename
? ? ? ? self.mode = mode
? ? def __enter__(self):
? ? ? ? self.fp = open(self.filename,self.mode)
? ? ? ? print('__enter__')
? ? ? ? return self.fp
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? self.fp.close()
? ? ? ? # print('__exit__')
? ? ? ? print(exc_type)
? ? ? ? print(exc_val)
? ? ? ? print(exc_tb)
? ? ? ? # 如果不想拋出異常,那么返回True,會自動的吸收這個(gè)異常
? ? ? ? return True
with FileOpener('abc.txt','w') as fp:
? ? fp.write('hello world')
? ? a = 1
? ? c = a/0