1、with as 简介
有一些操作,可能事先需要设置,事后做清理工作。对于这种场景,Python的with
语句提供了一种非常方便的处理方式。
例如,
with open("/tmp/foo.txt") as file:
data = file.read()
相当于 try finally代码:
file = open("/tmp/foo.txt")
try:
data = file.read()
finally:
file.close()
2、with as语句中调用构造函数
使用with as
时,可以在with as
语句中调用构造函数,也可以在之前调用,具体有什么区别,示例代码如下,
class Test: def __init__(self, name): self.name = name def __enter__(self): print(f'entering {self.name}') def __exit__(self, exctype, excinst, exctb) -> bool: print(f'exiting {self.name}') return True with Test('first') as test: print(f'in {test.name}') test = Test('second') with test: print(f'in {test.name}')
输出:
entering first
exiting first
entering second
in second
exiting second
可以看出with as
中没有调用构造函数,__enter__
方法应该返回上下文对象。with as
使用__enter__
的返回值来确定要给的对象。由于__enter__
不返回任何内容,它隐式返回None
,因此test为None
。之后的test.name
就引发了一个错误,调用了Test('first').__exit__
返回True
,可以改成如下:
class Test:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f'entering {self.name}')
return self
def __exit__(self, exctype, excinst, exctb) -> bool:
print(f'exiting {self.name}')
return True
with Test('first') as test:
print(f'in {test.name}')
test = Test('second')
with test:
print(f'in {test.name}')