python whit as

with as的用法:

with expression as variable:
  with block

with所求值的对象(expression)必须有一个__enter__()方法,一个__exit__()方法;每次都会先执行__enter__()方法,最后执行__exit__()方法。

举例说明:

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:", sample

执行结果:

In __enter__()
sample: Foo
In __exit__()

以上程序的执行顺序:

1. __enter__()方法被执行

2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample'

3. 执行代码块,打印变量"sample"的值为 "Foo"

4. __exit__()方法被调用

with-as语句使用举例

(1)打开文件的例子 

with-as语句最常见的一个用法是打开文件的操作,如下:

with open("decorator.py") as file:
  print file.readlines()
首先open("decorator.py")返回一个对象或者其本身就是一个对象,调用该对象下的__enter__()方法,然后执行print file.readlines(),最后再调用__exit__()方法。
参考博客:https://www.jb51.net/article/135285.htm
posted @ 2019-07-01 10:38  JQS  阅读(215)  评论(0编辑  收藏  举报