gpt4 book ai didi

python - 在 Python 中充当装饰器和上下文管理器的函数?

转载 作者:IT老高 更新时间:2023-10-28 20:34:12 25 4
gpt4 key购买 nike

这可能有点太过分了,但主要是出于好奇..

是否有可能有一个可调用的对象(函数/类)同时充当 上下文管理器和装饰器:

def xxx(*args, **kw):
# or as a class

@xxx(foo, bar)
def im_decorated(a, b):
print('do the stuff')

with xxx(foo, bar):
print('do the stuff')

最佳答案

从 Python 3.2 开始,对此的支持甚至包含在标准库中。派生自类 contextlib.ContextDecorator可以轻松编写可以用作装饰器或上下文管理器的类。这个功能可以很容易地向后移植到 Python 2.x——这是一个基本的实现:

class ContextDecorator(object):
def __call__(self, f):
@functools.wraps(f)
def decorated(*args, **kwds):
with self:
return f(*args, **kwds)
return decorated

从此类派生上下文管理器,并像往常一样定义 __enter__()__exit__() 方法。

关于python - 在 Python 中充当装饰器和上下文管理器的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com