python中的装饰器简介

1.什么是装饰器

把一个函数当作参数,返回一个替代版的函数,本质上就是一个返回函数的函数

简单来说就是"在不改变原函数的基础上,给函数增加功能”

例如下面的例子

def func1():
    print('hello python')

def outer():
    print('~~~~~~~~~~~~~~')

func1()
outer()

如果我们使用装饰器来实现上面的功能~

def func1():
    print('hello python')
def outer(a):
    def inner():
        a()
        print('~~~~~~~~~~~~~~~')
    return inner


func1 = outer(func1)
func1()

这个装饰器的运行为,将func1函数传给形参a,然后调用a,即func1,然后输出~~~~~~~~~~~,所以输出结果为

下面还有一个例子来帮助大家理解一下装饰器

port time

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

@decorator
def f1():
    print('This is a function')
f1()

这里的@decorator的意思是调用decorator函数,他下面的函数像当于原函数,而decorator函数相当于修饰元函数(添加功能的)函数

上面这样写,跟下面这样写一样

import time

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

#@decorator
def f1():
    print('This is a function')

f1 = decorator(f1)
f1()

这两个函数其运行的过程为,首先将f1传给形参func,然后运行decorator里面的函数,具体为首先输出时间,然后调用f1函数

猜你喜欢

转载自blog.csdn.net/weixin_40543283/article/details/86775390