本文主要介绍Python中,使用with as语句时,不同情况调用构造函数的总结,以及相关的示例代码。

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}')

推荐文档