Python装饰器仅调用一次 多次调用被装饰函数未触发打印原因
问题原因解析
- Python装饰器的执行时机是被装饰函数定义时,而非每次调用被装饰函数时。当解释器解析到
@is_authenticated_decorator标注create_blog_post函数的代码段时,就会立刻执行一次is_authenticated_decorator(create_blog_post),把返回的wrapper函数赋值给原create_blog_post变量,这个过程全局只会执行一次,因此你写在装饰器内部、wrapper外部的print('Decorator called')语句只会输出一次。 - 后续你两次调用的
create_blog_post,本质上调用的是装饰器执行后返回的wrapper函数,不会再重新执行is_authenticated_decorator本身,自然不会再触发第二行打印。
如果你需要每次调用被装饰函数时都打印对应内容,只需要把print('Decorator called')移动到wrapper函数内部即可,修改后示例如下:
def is_authenticated_decorator(function): def wrapper(*args, **kwargs): print('Decorator called') # 移到此处即可 user = args[0] if user.is_logged_in: function(user) return wrapper
修改后运行代码就会和你预期的输出一致。
内容的提问来源于stack exchange,提问作者Arvind Kumar Avinash
相关产品推荐
相关产品推荐

