Python有一個非常好用的東西,python with as,使用的基本思想大致是,具有所需值的對象必須有一個enter()方法和一個exit()方法。讓我們舉一個簡單的例子來說明您在使用時做了什么,一文看懂python3 with用法。
class Sample: def __enter__(self): print "In __enter__()" return "Foo" def __exit__(self, type,value, trace): print "In__exit__()" def get_sample(): return Sample() with get_sample() as sample: print(sample)
1.首先舉個例子
with open("/tmp/aaa.txt") as file:
data = file.read()
2.with的作用
使用with后不管with中的代碼出現什么錯誤,都會進行對當前對象進行清理工作。
例如file的file.close()方法,無論with中出現任何錯誤,都會執行file.close()方法
3.使用的條件
只有支持了上下文管理器的對象,才可以使用。
上下文管理的對象,如下所示
1 file
2 decimal.Context
3 thread.LockType
4 threading.Lock
5 threading.RLock
6 threading.Condition
7 threading.Semaphore
8 threading.BoundeSemaphore
ps :上下文管理器就是指:這個管理器就是在對象內實現了兩個方法:__enter__() 和__exit__()
我的其他Python文章:
wxPython Modal Dialog模式對話框,Python對話框中打開對話框