如果我们的函数带有参数如何来装饰:
def person(age): print("xl is %s years old!" % (age)) # 我们定义一个函数person # 调用函数person person(18) # 执行结果: xl is 18 years old! # 如果: person(-10) # 执行结果: xl is -10 years old! # 没有哪个人的年龄是是负数 # 写一个装饰器如果你给的年龄是负数的话,就默认为0,0总比负数好 def outer(func): def inner(age): if age < 0: age = 0 func(age) return inner say = outer(say) say(-10) # 执行结果 xl is 0 years old!
把装饰器函数和person函数调换一下位置:
def outer(func): def inner(age): if age < 0: age = 0 func(age) return inner # # 在python2.4 支持使用@符号 # 使用@符号将装饰器应用到函数 @outer def person(age): print("xl is %s years old!" % (age)) # 每次调用装饰器都要写成say=outer(say)的话, 很麻烦 # 在使用的@之后就可以不用每次再写say = outer(say) say = outer(say) say(-10) # 执行结果 xl is 0 years old!
文章来源: 装饰器浅解析(带参数的函数)2