Skip to content

Instantly share code, notes, and snippets.

@islishude
Last active August 27, 2019 11:51
Show Gist options
  • Save islishude/8b0ce471d47e59b0f53e01cc86aba571 to your computer and use it in GitHub Desktop.
Save islishude/8b0ce471d47e59b0f53e01cc86aba571 to your computer and use it in GitHub Desktop.
python with...as 语法
class Sample:
def __init__(self):
pass
def __enter__(self):
return self
def __exit__(self, type, value, trace):
# 如果语句体的退出是由异常导致的,并且来自 __exit__() 方法的返回值为假,则该异常会被重新引发。
# 如果返回值为真,则该异常会被抑制,并会继续执行 with 语句之后的语句。
print("with...as")
return True
def do_something(self):
bar = 1 / 0
return bar + 10
try:
sample = Sample()
sample.do_something()
except Exception:
pass
finally:
print("try...catch")
# 发起调用上下文管理器的 __enter__() 方法。
# 如果 with 语句中包含一个目标,来自 __enter__() 的返回值将被赋值给它。
# with 语句会保证如果 __enter__() 方法返回时未发生错误,则 __exit__() 将总是被调用。
# 因此,如果在对目标列表赋值期间发生错误,则会将其视为在语句体内部发生的错误。
# see https://docs.python.org/zh-cn/3/reference/compound_stmts.html#the-with-statement
with Sample() as sample:
sample.do_something()
print("not runing")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment