python中with as 用法

with as 呢,就是个python控制流语句,像 if ,while。
with as 语句的结构:

with expression [as variable]:  
    with-block  

with expresion as variable的执行过程是

  • 首先执行_enter_函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略。
  • 然后,开始执行with-block中的语句,不论成功失败(比如发生异常、错误,设置sys.exit()),在with-block执行完成后,会执行_exit_函数。

等价于:
try:
执行 _enter_的内容
执行 with_block.
finally:
执行 _exit_内容

    附:try finally功能演示例子 (顺序执行try内语句,如果有错跳进except报错语句执行,随后直接进入finally。不管是否有错,都要执行finally)
try:
    a=1/2
    print (a)  
    b = 1 / 0 # an abnormal number/variable  
    print (b)
    c = 2 / 1 # a normal number/variable  
    print (c)  
except NameError:
    print("ops")
except ZeroDivisionError:
    print("wrong math")
except:
    print("error")
#else:
#    print("no error")
finally:
    print("end")

例子1(无报错):

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  

执行步骤:

  • 调用get_sample()函数,返回Sample()类;

  • 执行Sample类中的enter()方法,打印”In__enter_()”字符串,并将字符串“Foo”赋值给as后面的sample变量;

  • 执行with-block码块,即打印”sample: %s”字符串,结果为”sample: Foo”
  • 执行with-block码块结束,返回Sample()类,执行类方法exit()。因为在执行with-block码块时并没有错误返回,所以type,value,trace这三个arguments都没有值。直接打印 print “In__exit__()”

结果:

In __enter__()
sample:  Foo
In __exit__()

例子2(有报错):

class Sample:  
    def __enter__(self):  
        return self  
    def __exit__(self, type, value, trace):  
        print "type:", type  
        print "value:", value  
        print "trace:", trace  
    def do_something(self):  
        bar = 1/0  
        return bar + 10  
with Sample() as sample:  
    sample.do_something()  

结果:

type: <class 'ZeroDivisionError'>
value: division by zero
trace: <traceback object at 0x000000000EC6F7C8>
Traceback (most recent call last):

  File "<ipython-input-16-1f63b4f99f4d>", line 13, in <module>
    sample.do_something()

  File "<ipython-input-16-1f63b4f99f4d>", line 9, in do_something
    bar = 1/0

ZeroDivisionError: division by zero
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值