天天看點

Python __exit__,__enter__函數with語句的組合應用

__exit__,__enter__函數with語句的組合應用

by:授客 QQ:1033553122

簡介

設計對象類時,我們可以為對象類新增兩個方法,一個是__enter(self)__,一個是__exit__(self, exc_type, exc_val, exc_tb)。

__enter(self)__

負責傳回一個值,該傳回值将指派給as子句後面的var_name,通常傳回對象自己,即“self”。函數優先于with後面的“代碼塊”(statements1,statements2,……)被執行。

__exit__(self, exc_type, exc_val, exc_tb)

執行完with後面的代碼塊後自動調用該函數。with語句後面的“代碼塊”中有異常(不包括因調用某函數,由被調用函數内部抛出的異常) ,會把異常類型,異常值,異常跟蹤資訊分别指派給函數參數exc_type, exc_val, exc_tb,沒有異常的情況下,exc_type, exc_val, exc_tb值都為None。另外,如果該函數傳回True、1類值的Boolean真值,那麼将忽略“代碼塊”中的異常,停止執行“代碼塊”中剩餘語句,但是會繼續執行“代碼塊”後面的語句;如果函數傳回類似0,False類的Boolean假值、或者沒傳回值,将抛出“代碼塊”中的異常,那麼在沒有捕獲異常的情況下,中斷“代碼塊”及“代碼塊”之後語句的執行

with xxx as var_name:

# 代碼塊開始

statements1

statements2

……

# 代碼塊結束

# 代碼快後面的語句

statements after code block

代碼示範1

#!/usr/bin/env python
      
# -*- coding:utf-8 -*-
      
__author__ = 'laiyu'
      
class User(object):
      
def __init__(self, username, password):
      
self._username =  username
      
self._password = password
      
    @property
      
def username(self):
      
return self._username
      
    @username.setter
      
def username(self, username):
      
self._username = username
      
    @property
      
def password(self):
      
return self._password
      
    @password.setter
      
def password(self, password):
      
self._password = password
      
def __enter__(self):
      
print('auto do something before statements body of with executed')
      
return self
      
def __exit__(self, exc_type, exc_val, exc_tb):
      
print('auto do something after statements body of with executed')
      
if __name__ == '__main__':
      
    boy = User('shouke', 'shouke2014')
      
print(boy.password)
      
with User('shouke', '2014') as user:
      
print(user.password)
      
print('---------end-----------')
      
運作結果
      
Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用
如上,代碼塊運作前調用了__enter__函數,代碼塊運作完,自動調用了__exit__函數
      

代碼示範2

更改上述部分代碼如下,繼續運作
      
def __exit__(self, exc_type, exc_val, exc_tb):
      
print('auto do something after statements body of with executed')
      
print('exc_type:', exc_type)
      
print('exc_val:', exc_val)
      
print('exc_tb:', exc_tb)
      
return False
      
if __name__ == '__main__':
      
    boy = User('shouke', 'shouke2014')
      
print(boy.password)
      
with User('shouke', '2014') as user:
      
print(user.password)
      
12/0
      
print('after execption')
      
print('---------end-----------')
      
運作結果
      
Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用
對比實驗:
      
在上述的基礎上繼續修改代碼
      
def __exit__(self, exc_type, exc_val, exc_tb):
      
print('auto do something after statements body of with executed')
      
print('exc_type:', exc_type)
      
print('exc_val:', exc_val)
      
print('exc_tb:', exc_tb)
      
return True
      
if __name__ == '__main__':
      
    boy = User('shouke', 'shouke2014')
      
print(boy.password)
      
with User('shouke', '2014') as user:
      
print(user.password)
      
12/0
      
print('after execption')
      
print('---------end-----------')
      
運作結果:
      
Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用
注意:
      
1、抛異常後,代碼塊中剩餘的語句沒有再繼續運作
      
2、如果在上述的基礎上,把代碼中的 12/0剪切後放到password(self)中,抛出異常的異常資訊是不會傳遞給__exit__函數的
      
@property
      
def password(self):
      
12/0
      
return self._password
      
運作結果如下,
      
Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用

作者:授客

QQ:1033553122

全國軟體測試QQ交流群:7156436

Git位址:https://gitee.com/ishouke

友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!

作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額随意,您的支援将是我繼續創作的源動力,打賞後如有任何疑問,請聯系我!!!

           微信打賞                       

支付寶打賞                  全國軟體測試交流QQ群  

Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用
Python __exit__,__enter__函數with語句的組合應用