简介:
本文主要介绍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}')
了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。