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接口(附代码)