with一个对象,自动触发__enter__方法

class Foo(object):
    def __init__(self):
        pass

    def __enter__(self):
        print("__enter__")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")


obj = Foo()
with obj:
    print("xxx")
    
# 结果
"""
__enter__
xxx
__exit__
"""
原文地址:https://www.cnblogs.com/believepd/p/10375148.html