python快速學習系列(9) 上下文管理器

2021-09-02 07:41:43 字數 4121 閱讀 5762

上下文管理器context manager

-為什麼要學context manager?

·類似於decorator,tensorflow裡面出現了不少context manager

·pythonic的**復用工具,適用於所有有始必有終模式的**復用

·減少錯誤,降低編寫**的認知資源(比如開啟檔案需要關閉檔案)

·提高**可讀性

1.什麼是context manager?與with語句是何關係?

context manager is a protocol for python with statement

執行時機:(雙下劃線很不友好,不用**表示會被認為是強調。。。)

·__init__():進入with語句時執行(optional,可實現也可不實現)

·__enter__():進入with**塊之前執行

·__exit__():離開with**塊之後執行

方法引數:

·__init__():context manager的初始化引數,自行定義

·__enter__():無引數

·__exit__():三個位置引數(type,instance,traceback)

說明:如果沒有exception丟擲,__exit__()的三個位置引數置為none

context manager通用結構:

class foo:

def __init__(self,stable=false):

self.x = 0

self.stable = stable

print("__init__() called.")

def __enter__(self):

print("__enter__() called.")

return self

def __exit__(self,exc_type,exc_value,exc_traceback):

print("__exit__() called.")

if exc_type:

print(f'exc_type:')

print(f'exc_value:')

print(f'exc_traceback:')

if self.stable:#當stable=true時,即使出現異常也是返回true,也就是說抑制異常

return true

def add_one(self):

self.x += 1

def show_x(self):

print(self.x)

def main():

foo_cm_l = foo()

print('hello!')

with foo_cm_l as foo_cm:

foo_cm.show_x()

foo_cm.add_one()

foo_cm.show_x()

print('hello')

with foo() as foo_cm:

foo_cm.show_x()

foo_cm.add_one()

foo_cm.show_x()

print('hello')

with foo_cm_l as foo_cm:

foo_cm.show_x()

foo_cm.add_one()

foo_cm.show_x()

print('hello')

with foo(true) as foo_cm:

1 / 0

print('hello')

with foo_cm_l as foo_cm:

1 / 0

ifname== 『main』:

main()

#以上**的目的是為了看i)異常能否被抑制 ii)生命週期 結果如下

__init__() called.

hello!

__enter__() called.01

__exit__() called.

hello

__init__() called.

__enter__() called.01

__exit__() called.

hello

__enter__() called.12

__exit__() called.

hello---

__init__() called.

__enter__() called.

__exit__() called.

exc_type:exc_value:division by zero

exc_traceback:hello----

__enter__() called.

__exit__() called.

exc_type:exc_value:division by zero

exc_traceback:traceback (most recent call last):

file "t.py", line 59, in main()

file "t.py", line 56, in main

1 / 0

zerodivisionerror: division by zero

2.context manager如何使用

·成對出現的模式——上下文管理器使用的訊號:

-open-close

-setup-teardown

-lock-release

-change-reset

-enter-exit

-start-stop

-create-delete

f = open() ---> f.close()

with open(path,mode) as f:

f.read()

#這裡就不用管f.close()了,因為在退出的時候,會自動呼叫

2)確保不同執行緒之間訪問共享資源時的執行緒鎖一定會釋放

with threading.rlock():

access_resource()

#同理,會自動釋放

3)管理資料庫的連線資源

conn = sqlite3.connect()

with conn:

conn.execute("some sql operations")

conn.execute("some other sql operations")

#會自動呼叫commit函式,斷開連線等等

4)對某一塊**進行執行時間測量:

conn.request('get','/')3.乙個功能的**實現與其工程化的區別

·某種或某些情況下可用vs任何情況下都可用

·資源足夠的情況下可用vs有限的資源下可用

·自己可以執行起該程式vs任何人可自行執行

·自己可以繼續開發修改vs任何人可繼續開發修改

·強調功能本身vs強調:可用性、可擴充套件、效能、資源占用、安全、快速開發、容易交接、不易犯錯

python快速學習系列(8) 異常處理

異常通常出現的處理方式 條件語句 if else 異常處理 try except else finally 1.python中的異常和相關語法 exception python內建的異常類 raise 丟擲異常 try 嘗試執行以下語句 except 在try語句之後,捕獲某個異常,為空則捕獲全部異...

Python教程系列(9) 函式

python教程系列函式 如下 python教程之函式 python中使用def 定位函式 格式為 def num a,b python函式建立及呼叫 建立函式名稱為num的函式,計算a b的和 def num a,b c a b print c 呼叫num函式,輸入結果為7 num 2,5 pri...

學python(9) 快速排序

第一種 快速排序 defkp ls 判斷要操作的列表長度是否大於1 if len ls 1 如果列表只有乙個數,則直接返回列表 return ls 定義兩個列表儲存相對較大的數和相對較小的數 maxa mina 這次選擇用第乙個數作為分割標準 遍歷除了第乙個資料的列表 for i in ls 1 判...