ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# with with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。 ```python class Sample: def __enter__(self): print("In __enter__()") return "Foo" def __exit__(self, type, value, trace): print("In __exit__()") def get_sample(): return Sample() with get_sample() as sample: print("sample:" + sample) ''' output: In __enter__() # __enter__()方法被执行, 赋值给变量'sample' sample:Foo # 执行代码块,打印变量"sample"的值为 "Foo" In __exit__() # __exit__()方法被调用 ''' ```