【发布时间】:2018-11-22 05:22:00
【问题描述】:
两者的主要区别是什么?我一直在研究 Python 并遇到了它们。装饰器本质上是一个包装另一个函数的函数,您可以在特定函数执行之前和之后执行任何操作。
def my_decorator(some_function):
def wrapper(*args, **kwargs):
print("Do something before the function is called")
some_function(*args, **kwargs)
print("Do something after the function is called")
return wrapper
@my_decorator
def addition(a, b):
result = a+b
print("Addition of {} and {} is {}".format(a,b,result))
但是在学习了 Context Manager 之后,我忍不住注意到它也有一个 enter 和 exit ,您可以在其中执行大多数类似的操作。
from contextlib import contextmanager
@contextmanager
def open_file(path, mode):
the_file = open(path, mode)
yield the_file
the_file.close()
files = []
for x in range(100000):
with open_file('foo.txt', 'w') as infile:
files.append(infile)
for f in files:
if not f.closed:
print('not closed')
yield 之前的所有内容都作为“进入”的一部分,而在“退出”之后的所有内容。
尽管上下文管理器和装饰器在语法上有所不同,但它们的行为可以被视为相似。那么区别是什么呢?应该使用其中任何一个的不同场景是什么?
【问题讨论】:
标签: python python-decorators contextmanager