zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    第二周总结
    币值转换
    抓老鼠
    秋季学习总结
    第七周作业
    第六周作业
    2019年春季第五周
    2019年春季学期第四周作业
    2019年春季学期第三周作业
    2019年春季学期第二周作业
  • 原文地址:https://www.cnblogs.com/jiaoqiang/p/11112758.html
Copyright © 2011-2022 走看看