zoukankan      html  css  js  c++  java
  • python with原理

    在python2.5+中可以用with来保证关闭打开的文件

    with open('hello.txt') as f:
        do some file operations

    为什么要引入with呢?

    在之前如果要保证关闭文件需要这样: 

    f = open('hello.txt')
    try:
      do some file operations
    finally:
      f.close()

    为了简化这些操作,pyhton2.5中引入with,在进入with时python会自动调用对象的__enter__ 函数,

    离开with时会调用 __exit__ 函数,如下所示。

    class SomeThing(object):
        def __enter__(self):
            set things up
            return self
        def __exit__(self, type, value, traceback):
            tear things down

    是不是很简单?

    比如我们可以实现一个自动释放资源的connection类

    class Connection(object):
        def __enter__(self):
        print 'enter'
        return self
    
        def __exit__(self, type, value, traceback):
        print 'exit'
    
        def say_hi(self):
        print 'hello, world'
    
    def open_connection():
        return Connection()
    
    with open_connection() as conn:
        conn.say_hi()

    程序输出为:

    enter
    hello, world
    exit
  • 相关阅读:
    Docker
    Web
    爬虫
    Python
    软件脱壳
    网络抓包
    HTTPS单向认证,双向认证
    新版无完整背景图片滑块验证码
    Frida Hook
    闭包函数与装饰器
  • 原文地址:https://www.cnblogs.com/goodhacker/p/3872336.html
Copyright © 2011-2022 走看看