gpt4 book ai didi

python - 函数如何知道调用函数的装饰器

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:38 25 4
gpt4 key购买 nike

我有两个装饰器,@timeout 和@retry代码是这样的

@timeout(seconds=1)
def func_inner(expire):
time.sleep(expire)

@retry(
count=2,
message="Failed command after {expire} seconds",
)
def func(expire):
func_inner(expire)

我只想知道 func() 方法如何知道 func_inner 有一个装饰器@timeout?提前致谢!

最佳答案

这段代码:

@timeout(seconds=1)
def func_inner(expire):
time.sleep(expire)

本质上等于:

def func_inner(expire):
time.sleep(expire)

func_inner = timeout(seconds=1)(func_inner)

方法 func 简单地调用了 func_inner(expire),这与调用 timeout(seconds=1)(func_inner)(expire) 是一样的> 因为装饰器重新定义了函数。

关于python - 函数如何知道调用函数的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432178/

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