【问题标题】:Python decorator without passing a function as argument没有将函数作为参数传递的 Python 装饰器
【发布时间】:2019-07-02 12:09:22
【问题描述】:

我正在学习编写 python 装饰器。以下是两个例子。

示例 1:

def dec():
    def wrapper(func):
        print(func)
        return func

    return wrapper

@dec
def hello():
    print('hello')

示例 2:

def dec(name):
    def wrapper(fn):
        print(fn)
        return fn
    return wrapper

@dec('a')
def hello(x):
    print(x)

所以我的问题是为什么示例 1 会抛出 dec() takes 0 positional arguments but 1 was given 的异常,而示例 2 运行良好。

【问题讨论】:

  • 在第一个示例中,您需要像这样调用dec@dec()。如果你想像你一样使用它,你的装饰器本身必须具有该功能(即不需要包装器)。

标签: python decorator


【解决方案1】:

机器人示例不正确。装饰器的外部函数(在这种情况下为 dec)必须接受一个参数,即它所装饰的函数。

所以示例 1 应该如下所示:

def dec(func):
    def wrapper():
        print(func)
        return func

    return wrapper

@dec
def hello():
    print('hello')

hello()

如果您尝试调用hello(装饰函数),示例二不会立即崩溃。 要让装饰器接受参数,您需要另一个级别的嵌套。 所以示例 2 应该如下所示:

def dec_args(name):
    def dec(func):
        def wrapper():
            print(func)
            print(name)
            return func

        return wrapper
    return dec

@dec_args('a')
def hello():
    print('hello')

hello()

内部装饰器函数 (wrapper) 应该采用传递给装饰器函数 (hello) 的参数。在这些情况下,您没有任何 还要注意wrapper 函数实际上并不需要返回funcwrapper 本质上是 func 的替代品。这就是装饰师所做的。它们用装饰器的内部函数替换你装饰的函数(通过使用装饰函数作为参数调用外部函数)。

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2020-03-22
    • 2018-12-04
    • 2014-07-21
    • 2017-09-08
    相关资源
    最近更新 更多