Python编程常用技巧,你全知道么?(13)

def __init__(self):

...

def __enter__(self):

# Initialize connection...

def __exit__(self type value traceback):

# Close connection...

with Connection() as c:

# __enter__() executes

...

# conn.__exit__() executes

这是在Python中实现上下文管理的最常见方法 , 但是有一种更简单的方法:

from contextlib import contextmanager

@contextmanager

def tag(name):

print(f\"<{name>\")

yield

推荐阅读