装饰器浅解析(带参数的函数)2

匿名 (未验证) 提交于 2019-12-03 00:36:02

如果我们的函数带有参数如何来装饰:

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!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!