解释 Python 的 '__enter__' 和 '__exit__' [英] Explaining Python's '__enter__' and '__exit__'

查看:32
本文介绍了解释 Python 的 '__enter__' 和 '__exit__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw this in someone's code. What does it mean?

    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

推荐答案

使用这些魔法方法 (__enter__, __exit__) 可以让您实现易于使用的对象使用 with 语句.

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement.

这个想法是它可以轻松构建需要执行一些清理"代码的代码(将其视为一个 try-finally 块).这里有更多解释.

The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally block). Some more explanation here.

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

A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):

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 语句一起使用(如果您使用 Python,则可能需要在文件顶部执行 from __future__ import with_statement2.5).

As explained above, use this object with the with statement (you may need to do from __future__ import with_statement at the top of the file if you're on Python 2.5).

with DatabaseConnection() as mydbconn:
    # do stuff

PEP343 -- 'with' 语句' 写得很好

这篇关于解释 Python 的 '__enter__' 和 '__exit__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆