【问题标题】:One call to decorator function suppressing the other one一个对装饰器函数的调用抑制另一个
【发布时间】:2021-11-29 18:37:28
【问题描述】:

来自以下代码

class User:
    def __init__(self, name):
        self.name = name
        self.is_logged_in = False


def is_authenticated_decorator(function):
    print('Decorator called')

    def wrapper(*args, **kwargs):
        user = args[0]
        if user.is_logged_in:
            function(user)

    return wrapper


@is_authenticated_decorator
def create_blog_post(user):
    print(f"This is {user.name}'s new blog post")


user_1 = User('John')
create_blog_post(user_1)  # 1

user_1.is_logged_in = True
create_blog_post(user_1)  # 2

我希望输出为

Decorator called
Decorator called
This is John's new blog post

相反,我得到的输出为

Decorator called
This is John's new blog post

当我注释掉标记为 #2 的语句时,我得到以下输出

Decorator called

为什么在 #2 存在的情况下这个输出会被抑制?

【问题讨论】:

  • 你只调用一次is_authenticated_decorator:当你定义create_blog_post时。

标签: python python-decorators


【解决方案1】:

is_authenticated_decorator 仅在将函数提供给装饰器时调用一次。被多次调用的是wrapper。要查看每次调用该函数时,print 应该在最终绑定到名称 create_blog_postwrapper 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2021-12-12
    • 1970-01-01
    • 2021-04-06
    • 2017-11-16
    • 2016-03-14
    • 1970-01-01
    • 2015-09-27
    相关资源
    最近更新 更多