python – 有没有办法在ContextDecorator中访问函数的属性/参数
发布时间:2020-12-20 13:51:40 所属栏目:Python 来源:网络整理
导读:我正在尝试使用 Python的contextlib.ContextDecorator类编写上下文管理器装饰器. 有没有办法在上下文管理器中访问修饰函数的参数? 这是我正在做的一个例子: from contextlib import ContextDecoratorclass savePen(ContextDecorator): def __enter__(self)
我正在尝试使用
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,param2): prevPen = dc.GetPen() # do stuff,possibly changing the pen style dc.SetPen(prevPen) 我已经搜索了contextlib的文档并且没有找到任何有用的东西. 有谁知道如何从ContextDecorator类中访问修饰函数的属性? EDIT1: 正如@chepner在this response所说,ContextDecorator是糖 def func(dc,param2): with savePen(): ... 并且它无法访问函数的参数. 但是,在这种情况下,使用savePen()运行的任何内容都可以访问函数参数dc,param1和param2.这让我觉得我应该能够使用ContextDecorator访问它们. 例如,这是有效的: def func(dc,param2): with savePen(): print(param1) 解决方法
contextlib.contextmanager似乎更合适.请注意,与其他任何内容一样,您无法从函数外部访问函数体的局部变量(无论如何都缺少内省黑客).
@contextlib.contextmanager def savePen(dc): prevPen = dc.GetPen() yield dc.SetPen(prevPen) with savePen(dc): func(dc,param2) 请注意,使用ContextDecorator,上下文管理器实例化时不带参数,即 @savePen() def func(dc,possibly changing the pen style 是语法糖(根据文件) def func(dc,param2): with savePen(): ... 所以没有办法告诉savePen使用哪个对象(dc). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |