python中的装饰器

装饰器的作用:给原有的函数添加新的功能但是不改变原有函数的代码

假设我们有如下的代码,其中hello函数可以打印“Hello”

1 def hello():
2     print('hello')

但是现在我们需要对hello函数添加新的功能,使其可以同时打印‘goodBye’,简单的我们可以使用下面的代码完成

1 def hello():
2     print('hello')
3     print('goodBye')

或者是这样的

def goodBye():
     print("goodBye")

def hello():
     goodBye()
     print("hello")

但是这样的话代码很麻烦,同时当我们需要撤销新加的功能的时候还需要修改源代码,这时就有了装饰器的写法

def goodBye(f):
    def f2():
        print("goodBye")
        return f()
    return f2


@goodBye
def hello():
    print("hello")

hello()

上面的代码等价与:

def goodBye(f):
     def f2():
          print("goodBye")
          return f()
     return f2

def hello():
     print("hello")

hello = goodBye(hello)
hello()
知之为知之,不知为不知
原文地址:https://www.cnblogs.com/bevishe/p/10972638.html