代码点读机 / Python / __enter__

__enter__ Python · 特殊方法

定义 with 语句进入时要执行的操作。

怎么用

def __enter__(self):

小例子

class 资源:
    def __enter__(self):
        print('打开')
        return self
    def __exit__(self, *a):
        print('关闭')
with 资源():
    pass

运行结果

打开
关闭

官方文档:https://docs.python.org/zh-cn/3/reference/datamodel.html#object.__enter__

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条