上下文協議管理

2022-07-27 02:54:08 字數 1338 閱讀 5971

with obj as f:

'**塊'

1.with obj ----》觸發obj.__enter__(),拿到返回值

2.as f----->f=返回值、

3.with obj as f 等同於 f=obj.__enter__()

4.執行**塊

一:沒有異常的情況下,整個**塊執行完畢後去觸發__exit__,它的三個引數都為none

二:有異常的情況下,從異常出現的位置直接觸發__exit__

a:如果__exit__的返回值為true,代表吞掉了異常

b:如果__exit__的返回值不為true,代表吐出了異常

c:__exit__的的執行完畢就代表了整個with語句的執行完畢

class

foo:

def__init__

(self,name):

self.name=name

def__enter__

(self):

print('

執行enter')

return

self

def__exit__

(self, exc_type, exc_val, exc_tb):

print('

執行exit')

print

(exc_type)

print

(exc_val)

print

(exc_tb)

return

true

with foo(

'a.txt

') as f:

print

(f)

print(asdfsaasdfasdfasdfasdfasfasdfasdfasdfasdfasfdasfd) #

觸發__exit__

print

(f.name)

print('

-----------------')

print('

-----------------')

print('

-----------------')

print('

-----------------')

print('

-----------------')

print('

-----------------')

print('

-----------------')

print('

000000000000000000000000000000000000000000000

')

上下文管理協議

class open def init self,name self.name name def enter self print 執行enter def exit self,exc type,exc val,exc tb print 執行exit with open a.txt as f with...

上下文管理協議

with open a.txt as f 開啟檔案,並自動關閉檔案 pass 上下文管理協議 class open def init self,name self.name name def enter self print 執行enter print self return self def ex...

python 上下文管理協議

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,ex...