码迷,mamicode.com
首页 > 编程语言 > 详细

python 小白(无编程基础,无计算机基础)的开发之路 辅助知识1 with...as

时间:2017-11-15 22:10:34      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:details   执行   val   例子   bsp   exp   调用   异常处理   res   

这个语法是用来代替传统的try...finally语法的。 

with EXPRESSION [ as VARIABLE] WITH-BLOCK 

基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。

[python] 
  1. file = open("/tmp/foo.txt")  
  2. try:  
  3.     data = file.read()  
  4. finally:  
  5.     file.close()  

使用with...as...的方式替换,修改后的代码是:

[python]
  1. with open("/tmp/foo.txt") as file:  
  2.     data = file.read()  
[python] 
  1. #!/usr/bin/env python  
  2. # with_example01.py  
  3.    
  4.    
  5. class Sample:  
  6.     def __enter__(self):  
  7.         print( "In __enter__()"  )
  8.         return "Foo"  
  9.    
  10.     def __exit__(self, type, value, trace):  
  11.         print( "In __exit__()"  )
  12.    
  13.    
  14. def get_sample():  
  15.     return Sample()  
  16.    
  17.    
  18. with get_sample() as sample:  
  19.     print( "sample:", sample  )

执行结果为
[python] 
  1. In __enter__()  
  2. sample: Foo  
  3. In __exit__()  

1. __enter__()方法被执行

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

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

4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。

python 小白(无编程基础,无计算机基础)的开发之路 辅助知识1 with...as

标签:details   执行   val   例子   bsp   exp   调用   异常处理   res   

原文地址:http://www.cnblogs.com/ManyQian/p/7840540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!