新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python中contextmanager裝飾的方法
(推薦操作系統(tǒng):windows7系統(tǒng)、python 3.9.1、DELL G3電腦。)

1、說(shuō)明
contextmanager 用于對(duì)生成器函數(shù)進(jìn)行裝飾,生成器函數(shù)被裝飾以后,返回的是一個(gè)上下文管理器,其 enter() 和 exit() 方法由 contextmanager 負(fù)責(zé)提供,而不再是之前的迭代子。被裝飾的生成器函數(shù)只能產(chǎn)生一個(gè)值,否則會(huì)導(dǎo)致異常 RuntimeError;產(chǎn)生的值會(huì)賦值給 as 子句中的 target,如果使用了 as 子句的話。下面看一個(gè)簡(jiǎn)單的例子。
2、裝飾器 contextmanager實(shí)例
from contextlib import contextmanager @contextmanager def demo(): print '[Allocate resources]' print 'Code before yield-statement executes in __enter__' yield '*** contextmanager demo ***' print 'Code after yield-statement executes in __exit__' print '[Free resources]' with demo() as value: print 'Assigned Value: %s' % value
以上就是python中contextmanager裝飾的方法,希望能對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文名稱:創(chuàng)新互聯(lián)Python教程:python中contextmanager裝飾的方法
當(dāng)前網(wǎng)址:http://fisionsoft.com.cn/article/dppgoch.html


咨詢
建站咨詢
