【发布时间】:2015-10-22 06:36:48
【问题描述】:
我正在尝试使用 Python 的 contextlib.ContextDecorator 类编写上下文管理器装饰器。
有没有办法在上下文管理器中访问修饰函数的参数?
这是我正在做的一个例子:
from contextlib import ContextDecorator
class savePen(ContextDecorator):
def __enter__(self):
self.prevPen = self.dc.GetPen() # AttributeError
return self
def __exit__(self, *exc):
self.dc.SetPen(self.prevPen)
return False
鉴于上述情况,这是:
@savePen()
def func(dc, param1, param2):
# do stuff, possibly changing the pen style
应该相当于:
def func(dc, param1, param2):
prevPen = dc.GetPen()
# do stuff, possibly changing the pen style
dc.SetPen(prevPen)
我搜索了 contextlib 的文档,但没有发现任何有用的信息。
有谁知道如何从 ContextDecorator 类中访问修饰函数的属性?
编辑1:
正如@chepner 在this response 中所说,ContextDecorator 是糖
def func(dc, param1, param2):
with savePen():
...
并且它不能访问函数的参数。
但是,在这种情况下,with savePen() 内部的任何运行都可以访问函数参数 dc、param1 和 param2。这让我觉得我应该能够使用 ContextDecorator 访问它们。
例如,这是有效的:
def func(dc, param1, param2):
with savePen():
print(param1)
【问题讨论】:
标签: python python-3.x python-decorators contextmanager