gpt4 book ai didi

python - 装饰器在没有被调用的情况下运行

转载 作者:行者123 更新时间:2023-11-30 23:07:35 25 4
gpt4 key购买 nike

我已经深入研究了 Python 装饰器,并正在研究一些向装饰器添加函数参数的方法。

我面临的问题与我想要在装饰器中进行递归同时仅在初始调用时设置一些变量有关。因此,在示例中,我只想在函数调用时打印一次消息。

现在它在函数定义上打印,而不是在函数调用上打印。请参阅此示例代码:

def recursiveCounter(message):
def decorater(func):
def wrapper(count):
func(count)
if count < 10:
count += 1
wrapper(count)

print message
return wrapper
return decorater


@recursiveCounter("hello I was called once")
def counter(count):
print count


counter(0)

最佳答案

下面我添加了注释来指示每行何时运行:

def recursiveCounter(message):  # when the decorator is defined
def decorater(func): # when the decorator is created - @recursiveCounter("hello I was called once")
def wrapper(count): # when the function is decorated - def counter(count): print count
func(count) # when the function is called - counter(0)
if count < 10: # when the function is called
count += 1 # when the function is called
wrapper(count) # when the function is called

print message # **when the function is decorated**
return wrapper # when the function is decorated
return decorater # when the decorator is created

如您所见,print message 行在函数被修饰时运行,而不是在函数被调用时运行。如果您希望它在调用函数时运行,则应该将其进一步缩进一级,以便它位于 wrapper 内,而不是 decorater 内。

<小时/>

如果您确实想保留递归实现,请重新排列包装器以定义和调用递归本身:

...
def wrapper(count):
def inner_wrapper(count):
if count < 10:
inner_wrapper(count + 1)
inner_wrapper(count)
print message

关于python - 装饰器在没有被调用的情况下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167680/

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