python里with as_Python之with as语句 (屌丝版)

0、我们都知道File对象,再拿到之后,释放要显式的调用close()方法,java的话,看下面

try {

File file = new File();

} catch (Exception e){

} finally {

file.close();

}

1、在Python中,不牛bi的写法,同java写法

file = open("/tmp/foo.txt")

data = file.read()

file.close()

file = open("/tmp/foo.txt")

try:

data = file.read()

finally:

file.close()

2、在Python中,with as 语句就是这么牛逼

with open("/tmp/foo.txt") as file:

data = file.read()

3、又在Flask框架中,看到这么一条语句,后面我再解答

with app.test_request_context()

4、先说说with怎么工作吧?

a、首先with所操作的对象,必须有两个重要的方法,__enter__、__exit__

Python对with的处理很聪明。

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

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

5、写个支持with as的例子

参照下面那位同学的

class Temp(object):

def __init__(self):

print '__init__(self)'

def __enter__(self):

print '__enter__(self)'

return self

def printName(self):

print "Temp"

def __exit__(self, type, value, trace):

print '__exit__(self)'

def getInstanceTemp():

temp = Temp()

return temp

with getInstanceTemp() as first:

first.printName()

输出结果:

__init__(self)

__enter__(self)

Temp

__exit__(self)

说下with使用时的步骤

0、先是getInstanceTemp()方法执行

1. getInstanceTemp()返回的Temp对象,会接着调用Temp对象的 __enter__()方法

2. __enter__()方法返回的值 - 这个例子中我返回的是self,即当前对象,赋值给变量first

3. 执行代码块,在这里我是调用了Temp的printName(self)方法

4. 代码块执行完后,Temp的__exit__()方法会被调用

6、照这么说,让我们去看看,他的

with open("/user/downloads/man") as first:

pass

open函数是__builtin__模块下的一个函数

def open(name, mode=None, buffering=None): # real signature unknown; restored from __doc__

"""

open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object. This is the

preferred way to open a file. See file.__doc__ for further information.

"""

return file('/dev/null')

#open返回的是一个file对象

file显然是__builtin__模块下的一个class

class file(object):

""" 省略其它代码"""

def __enter__(self): # real signature unknown; restored from __doc__

""" __enter__() -> self. """

return self

def __exit__(self, *excinfo): # real signature unknown; restored from __doc__

""" __exit__(*excinfo) -> None. Closes the file. """

pass

果然有enter、exit方法,而且enter方法返回的就是一个当前的file对象,所以,推断一切正确,偶也。

7、注意事项

with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有enter()和exit()方法即可。此例中,Sample()的enter()方法返回新创建的Sample对象,并赋值给变量sample

解读:也就是说,with后面跟着一个构造方法的调用,也一样,只要方法返回个对象就行,这里容易混淆,一定注意

8、关于with后面抛出异常,exit()被执行的情况,处理异常的能力,需要未来加固

际上,在with后面的代码块抛出任何异常时,exit()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给exit()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在exit方法当中。

因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

9、关于 as的省略

with getInstanceTemp():

print "pass"

输出结果:

__init__(self)

__enter__(self)

pass

__exit__(self)

也可以省略as、只是不要求enter()返回的对象进行赋值给一个变量而已,其它的步骤,一个不落下的依然会执行,这也就解释了Flask中

with app.test_request_context()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值