以前写过一篇装饰器文章,觉得少了点东西,今天特来补上,也就是带参数的装饰器,上篇文章写的不严谨
def logger(logs=""): def outer(f): def inner(*args): print("#####") ret = f(*args) return ret return inner if logs == "true": print("recoder logs") return outer @logger("true")###等价于@outer,先把true传进去,由于闭包的特性,outer和inner函数都可以拿到logs这个形参的参数 def adds(*args): sums = 0 for x in args: sums = sums + x return sums #x = outer(adds) print(adds(4, 5, 6))
执行结果如下
recoder logs
#####
15
根据返回值来看,函数执行是由外到内返回值???