我想了解这个代码中的装饰器行为
abc.py
def my_decorator_module(some_function):
def wrapper():
num = 10
if num == 10:
print('yess')
else:
print('no')
some_function()
print('print after some_function() called')
return wrapper()
并将此函数称为decorator
x.py
from abc import my_decorator_module
@my_decorator_module
def just_some_function():
print("Wheee!")
输出为
yess
Wheee!
print after some_function() called
当我执行x.py文件return me输出时,我没有调用x.py文件中的just_some_function()
事件,为什么?你知道吗
您没有显式地调用
just_some_function()
,但是您的“decorator”调用了,参见最后一行:这实际上是一个错误的实现-您的装饰程序不应该返回调用
wrapper
的结果,而是返回wrapper
函数本身:如果您不明白原因:
@decorator
语法只是语法糖,那么:实际上只是一个捷径:
因此,您的decorator必须返回一个函数对象(或任何可调用的FWIW),通常-但不一定-一些包装器将负责调用修饰函数(最好返回结果)。你知道吗
因为您在从外部装饰函数返回它之前已经调用了
wrapper
。别那么做。你知道吗tutorial you're following早先引入了返回函数的概念,而不是调用它们并返回它们的结果;这就是您需要在这里做的事情。你知道吗
相关问题 更多 >
编程相关推荐