面向对象编程(6) `__enter__`、`__exit__`
文件操作——上下问管理
with xxx as f:
pass
class Foo(object):
def __enter__(self):
return 666
def __exit__(self, exc_type, exc_val, exc_tb):
pass
obj = Foo()
# with 对象
在with后面跟着一个对象,会自动执行__enter__方法,会有一个返回值,返回值就是f
当with内部代码执行完毕会自动执行__exit__方法
浙公网安备 33010602011771号