python with as用法詳解,一文看懂python3 with用法


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文章:

python學了真的很有用嗎?當然!趕緊學,不學后悔!

wxPython Modal Dialog模式對話框,Python對話框中打開對話框

python @修飾符,這篇文章寫得明明白白的

python中的for循環底層原理詳解+python中for循環的原理

python調用api接口獲取數據,python如何調用api接口(附代碼)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM