try:
execution block ##正常执行模块
except A:
exc A block ##发生A错误时执行
except B:
exc B block ##发生B错误时执行
except:
other block ##发生除了A,B错误以外的其他错误时执行
else:
if no exception, jump to here ##没有错误时执行
finally:
final block ##总是执行
class Sample(object): # object类是所有类最终都会继承的类
def __enter__(self): # 类中函数第一个参数始终是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)
print(Sample) # 这个表示类本身 <class '__main__.Sample'>
print(Sample()) # 这表示创建了一个匿名实例对象 <__main__.Sample object at 0x00000259369CF550>
# 结果
In __enter__()
sample: Foo
In __exit__()
<class '__main__.Sample'>
<__main__.Sample object at 0x000001F4D3185A48>
示例2
class Sample:
def __enter__(self):
print("In __enter__()")
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
print("In __exit__()")
def do_something(self):
bar = 1 / 0
return bar + 10
with Sample() as sample:
sample.do_something()
# 结果
In __enter__()
type: <class 'ZeroDivisionError'>
value: division by zero
trace: <traceback object at 0x0000020707B95AC8>
In __exit__()
Traceback (most recent call last):
File ".\test.py", line 24, in <module>
sample.do_something()
File ".\test.py", line 19, in do_something
bar = 1 / 0
ZeroDivisionError: division by zero