with

context manager 
An object which controls the environment seen in a with statement by defining __enter__() and __exit__() methods. See PEP 343. 

所有具有context manager特性的对象都可以用with来简化编程。但是with有个问题就是__exit__()的调用的时间是不固定的,在小程序中一般是没有问题的,但是在大程序中可能会有不确定的bug。比较常用的是针对file对象,如下例子

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

我们可以用dir来查看file对象,可以发现file对象中是被定义了__enter__和__exit__的,所以可以用with来使用。查看方法

>>> f = open('tmp.py')
>>> dir(f)

同样,我们可以定义自己的可以用with的对象,只要实现__enter__和__exit__的动作即可。

#-*- coding:utf-8 -*-
class A:
	def __enter__(self):
		print('enter')
	
	#函数可以在手册中搜索__exit__看到
	def __exit__(self, exc_type, exc_value, traceback):
		print('exit')
	
	def test(self):
		return "I'm A"

if __name__ == '__main__':
	with A() as a:
		print("OK")

<完>

你可能感兴趣的:(with)