我個人對python的學習沒有那么系統,一開始想改造參考的類別庫,發現自己被一些語法問題卡頓,效率就低了,
于是就很想看看C#與python的比較,感覺這樣切語言適應起來會舒服些,我就自己寫吧,
買了一本書《深入理解Python特性》,嗯我總覺得那些像字典一樣的書實在難以提升我的學習興趣,這本書就很有意思,我就非常喜歡筆者像和你聊天一樣介紹“有意思的事情”這樣的博客體,
|
背景關系管理器 |
|
|
C# |
Python |
|
using(variable) {..} |
with variable: … |
|
IDispose
|
__enter__ __exit__ |
|
using陳述句中使用的型別必須可隱式轉換為”System.IDisposable” using括號內應該放一個實作了IDispose介面的變數, 下示一簡單例子:
|
with后接的變數需要實作: __enter__和__exit__ 比起C#用初始化來控制背景關系管理器的“開”, 我覺得用單獨的enter來控制會合理些, |
using static System.Console;
public class testDecorator : IDisposable
{
public testDecorator()
{
WriteLine("----------start----------");
}
public void Dispose()
{
WriteLine("---------- end ----------");
}
}
using (var td = new testDecorator())
{
WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmss")}");
}
|
import time
class manager_exectime():
def __init__(self):
self.lst = []
def __enter__(self):
self.lst.append(time.time())
return self
def __exit__(self, exc_type, exc_val, exc_tb):
_ = time.time()
print(f'--started at:{str(self.lst[-1])}')
|
|
當using的時候開辟新空間,dispose()用于釋放非托管資源; 像是讀取檔案用完需要close,表單物件也需要自行銷毀,資料庫連接斷開等; 當然,也可以用try{}catch{}finally{}于finally中釋放物件, 但using就是個語法糖嘛, |
上例代碼主要是一個執行時間的監控, 需要注意的是,exit的入參是規定這樣四個引數的,缺一個都不是解釋器識別的釋放函式,
|
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/96402.html
標籤:Python
上一篇:【Python3爬蟲】破解時光網登錄加密引數并實作模擬登錄
下一篇:洗掉單元格,列,行
