python按enter退出代码_解释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

解决方案

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

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.

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()

...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`__enter__`和`__exit__`是Python中用于上下文管理器的特殊方法。 `__enter__`方法在进入上下文管理器时被调用,它返回一个值,该值将被赋给`as`关键字后面的变量。通常,在`__enter__`方法中,我们执行一些准备工作,例如打开文件、建立数据库连接等。 `__exit__`方法在离开上下文管理器时被调用,它接收三个参数:异常类型、异常值和追溯信息。如果在上下文中没有发生异常,那么这三个参数都为None。如果在上下文中发生了异常,那么这三个参数将包含异常的相关信息。在`__exit__`方法中,我们可以执行一些清理工作,例如关闭文件、断开数据库连接等。 下面是一个使用上下文管理器的示例: ```python class MyContextManager: def __enter__(self): print("Entering the context") return "Hello" def __exit__(self, exc_type, exc_value, traceback): print("Exiting the context") if exc_type is not None: print(f"Exception: {exc_type}, {exc_value}") with MyContextManager() as value: print(value) ``` 输出结果为: ``` Entering the context Hello Exiting the context ``` 在这个示例中,`MyContextManager`是一个自定义的上下文管理器类。在`__enter__`方法中,我们打印了进入上下文的消息,并返回了一个字符串"Hello"。在`__exit__`方法中,我们打印了离开上下文的消息,并检查是否有异常发生。 在`with`语句中,我们创建了一个`MyContextManager`的实例,并将其赋值给`value`变量。在进入上下文时,`__enter__`方法被调用,打印了"Entering the context",并返回了"Hello"。然后,我们打印了`value`的值,即"Hello"。最后,在离开上下文时,`__exit__`方法被调用,打印了"Exiting the context"。 通过使用上下文管理器,我们可以确保在进入和离开上下文时执行必要的操作,并且可以处理可能发生的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值