解释Python的'__enter__'和'__exit__'

发布于 2021-01-29 15:00:15

我在某人的代码中看到了这一点。这是什么意思?

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

from __future__ import with_statement#for python2.5

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s


print s
关注者
0
被浏览
82
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用这些魔术方法(__enter____exit__)使您可以实现可轻松用于该with语句的对象。

    这个想法是,它使构建需要执行一些“清除”代码的代码(将其视为一个try- finally块)变得容易。这里有更多的解释

    一个有用的例子是数据库连接对象(一旦对应的“ with”语句超出范围,它就会自动关闭连接):

    class DatabaseConnection(object):
    
        def __enter__(self):
            # make a database connection and return it
            ...
            return self.dbconn
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            # make sure the dbconnection gets closed
            self.dbconn.close()
            ...
    

    如上所述,将此对象与with语句一起使用(from __future__ import with_statement如果您使用的是Python
    2.5,则可能需要在文件顶部进行操作)。

    with DatabaseConnection() as mydbconn:
        # do stuff
    

    PEP343-‘with’语句’也有不错的写法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看