python中with用法講解
我們都知道打開文件有兩種方法:
- f = open()
- with open() as f:
這兩種方法的區(qū)別就是第一種方法需要我們自己關(guān)閉文件;f.close(),而第二種方法不需要我們自己關(guān)閉文件,無論是否出現(xiàn)異常,with都會自動幫助我們關(guān)閉文件,這是為什么呢?
我們先自定義一個類,用with來打開它:
class Foo():
def __enter__(self):
print("enter called")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit called")
print("exc_type :%s"%exc_type)
print("exc_val :%s"%exc_val)
print("exc_tb :%s"%exc_tb)
with Foo() as foo:
print("hello python")
a = 1/0
print("hello end")
執(zhí)行結(jié)果:
enter called Traceback (most recent call last): hello python exit called exc_type :<class 'ZeroDivisionError'> exc_val :division by zero File "F:/workspaces/python_workspaces/flask_study/with.py", line 25, in <module> a = 1/0 exc_tb :<traceback object at 0x0000023C4EDBB9C8> ZeroDivisionError: division by zero Process finished with exit code 1
我們看到,執(zhí)行結(jié)果的輸入順序,分析如下:
當我們with Foo() as foo:時,此時會執(zhí)行__enter__方法,然后進入執(zhí)行體,也就是:
print("hello python")
a = 1/0
print("hello end")
語句,但是在a=1/0出現(xiàn)了異常,with將會中止,此時就執(zhí)行__exit__方法,就算不出現(xiàn)異常,當執(zhí)行體被執(zhí)行完畢之后,__exit__方法仍然被執(zhí)行一次。
我們回到with open("file")as f: 不用關(guān)閉文件的原因就是在__exit__方法中,存在關(guān)閉文件的操作,所以不用我們手工關(guān)閉文件,with已將為我們做好了這個操作,這就可以理解了。
以上就是小編整理的相關(guān)內(nèi)容,如果大家有任何補充可以聯(lián)系腳本之家小編。
相關(guān)文章
Python操作Redis數(shù)據(jù)庫的詳細教程與應用實戰(zhàn)
Redis是一個高性能的鍵值存儲數(shù)據(jù)庫,支持多種類型的數(shù)據(jù)結(jié)構(gòu),如字符串、哈希表、列表、集合和有序集合等,在Python中,通過redis-py庫可以方便地操作Redis數(shù)據(jù)庫,本文將詳細介紹如何在Python代碼中操作Redis,需要的朋友可以參考下2024-08-08
pytorch加載自定義網(wǎng)絡權(quán)重的實現(xiàn)
今天小編就為大家分享一篇pytorch加載自定義網(wǎng)絡權(quán)重的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

