带参数的装饰器

装饰器也可以带参数.

def strong(msg):
    pass


@strong("abc")
def hello():
    pass


hello()

上面的语义相当于:

hello = strong("abc")(hello)

def strong(msg):
    def temp1(fun):
        def temp2():
            print("哈哈哈" + msg)

        return temp2

    return temp1


@strong("abc")
def hello():
    print("hello 代码")

hello()

带参数迭代器总结:

带参数的装饰器比较难理解.我们稍微总结一下.

  1. 先牢记一点, 能接受函数作为参数的只能是不带参数的装饰器

  2. 所以, 使用带参数的装饰器的时候, 需要在带参数的装饰器中返回一个不带参数的函数, 这个返回的函数就是作为一个不带参数的装饰器来使用.d = strong("abc"). d 就是用来做装饰器用的.

  3. 然后hello = d(hello)


Copyright © 李振超 2018 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-02-25 07:12:09

results matching ""

    No results matching ""