python学习(3)
python的aop:
首先,我们定义一个函数:
def my_function(): print("this is my function")
如果,我们想在这个函数执行前以及函数执行后,分别输出"before the function run"和"after the function run",那我们可以这么写,在函数体中,插入:
def my_function(): print("before the function run") print("this is my function") print("after the function run")
这样我们便可以实现我们想要的效果了。
但是,我们想要在很多函数中都要插入这样的代码,这样写就很麻烦,所以就有了另一种写法:
def simple_decorator(func): print("before the function run") func() print("after the function run") def my_function(): print("this is my function") simple_decorator(my_function)
这样写,我们也能得到我们所想要的结果,但是,还是需要去修改我们的代码,那我们就需要一种更简洁的方法了。
def normal_decorator(func): def wrapper(): print("before the function run") func() print("after the function run") return wrapper() def my_function(): print("this is my function") my_function = normal_decorator(my_function) my_function
我们通过在修饰函数中,再加一个包装函数,将我们所想要包装的函数,进行一次包装,再去运行,这样,就能更方便的去得到我们所想要的结果,并且不对原本的代码进行较大的修改。虽然这种方法已经足够的方便了,但是,如果这个函数要调用很多次,我们则需要去给它修饰很多次,所以,就有了更加方便的写法:
def normal_decorator(func): def wrapper(): print("before the function run") func() print("after the function run") return wrapper() @normal_decorator def my_function(): print("this is my function") my_function

浙公网安备 33010602011771号