python – 有没有办法在ContextDecorator中访问函数的属性参数?

python – 有没有办法在ContextDecorator中访问函数的属性参数?,第1张

概述我正在尝试使用 Python的contextlib.ContextDecorator类编写上下文管理器装饰器. 有没有办法在上下文管理器中访问修饰函数参数? 这是我正在做的一个例子: from contextlib import ContextDecoratorclass savePen(ContextDecorator): def __enter__(self): 我正在尝试使用 Python的contextlib.ContextDecorator类编写上下文管理器装饰器.

有没有办法在上下文管理器中访问修饰函数的参数?

这是我正在做的一个例子:

from contextlib import ContextDecoratorclass 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.contextmanagerdef 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).

总结

以上是内存溢出为你收集整理的python – 有没有办法在ContextDecorator中访问函数的属性/参数?全部内容,希望文章能够帮你解决python – 有没有办法在ContextDecorator中访问函数的属性/参数?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1197349.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存