python- with和上下文管理器

上下文管理协议: 包含 __enter__() 和 __exit__() 方法
上下文管理器: 支持 “上下文管理协议”的对象

1. 有 __enter__() 和 __exit__() 方法的对象才能用with操作

2. 如果一个对象/类没有上下文属性,可以自己写一个类,在类中定义__enter__() 和 __exit__() 方法,继承想要有上下文属性的类(即:通过继承的方法给类拓展一个上下文属性)

class MyClass(object):

    def __enter__(self):
        print('enter is running ...')
        # return 1

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit is running ...')

def main():
    myclass = MyClass()
    with myclass as f:   # f等于上面return的1
        print('with is running ...')

main()
原文地址:https://www.cnblogs.com/erchun/p/14089863.html