python装饰器(披着羊皮的狼)

发布时间:2019-05-12 19:12:04编辑:auto阅读(1936)

    python装饰器的作用是在不改变原有函数的基础上,对函数的功能进行增加或者修改。

    装饰器语法是python语言更加优美且避免很多繁琐的事情,flask中配置路由的方式便是装饰器。

    首先python中一个函数也是可以当做一个对象进行传递的。

     1 def sheep(f):
     2     def she():
     3         print("I'm a sheep")
     4         return f()
     5     return she
     6 
     7 @sheep
     8 def wolf():
     9     print("I'm a wolf")
    10 
    11 if __name__ == "__main__":
    12     wolf()

    输出结果为

    I'm a sheep
    I'm a wolf

    上面代码相当于 

    wolf = sheep(wolf)
    wolf()

    带参数的装饰器

     1 def change(a):
     2     def sheep(f):
     3         def she():
     4             print("I'm a sheep")
     5             f()
     6             print("you're not ,you're {} sheep".format(a))
     7         return she
     8     return sheep
     9 
    10 @change("fake")
    11 def wolf():
    12     print("I'm a wolf")
    13 
    14 if __name__ == "__main__":
    15     wolf()

    结果:

    I'm a sheep
    I'm a wolf
    you're not ,you're fake sheep

    相当于

    wolf = change("fake")(wolf)
    wolf()

    其实函数名此时发生了改变

    wolf.__name__的值为she

    解决办法为使用functools.wraps

     1 import functools
     2 
     3 def change(a):
     4     def sheep(f):
     5         @functools.wraps(f)
     6         def she():
     7             print("I'm a sheep")
     8             f()
     9             print("you're not ,you're {} sheep".format(a))
    10         return she
    11     return sheep
    12 
    13 def wolf():
    14     print("I'm a wolf")
    15 
    16 if __name__ == "__main__":
    17     wolf = change("fake")(wolf)
    18     wolf()

     

关键字