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__
"""

 

猜你喜欢

转载自www.cnblogs.com/believepd/p/10375148.html
0条评论
添加一条新回复