pyhthon基础知识【4】:装饰器原理

本节内容:
1、装饰器概述
2、高阶函数
3、嵌套函数
4、实现装饰器
----------------------------------------------------------------------------/---------------------------------------------------------------
1、装饰器概述
1.1 装饰器本质是一个函数,用于装饰其他的函数(即给其他函数加上某些功能)
1.2 装饰器基本的原则:
(1)不改变被装饰函数的源代码
(2)不改变被装饰函数的调用方式
1.3 装饰器的基本原理即  高阶函数+嵌套函数  实现

2、高阶函数
2.1 高阶函数即是可以把函数当做一个实参传给另一个函数,也可被某个函数当做返回值返回
2.2 高阶函数特性
高阶函数1:不改变函数的源代码
import time 

def test1( ):
    time.sleep(1)
    print("in the test1")

#这个函数在不改变test1函数源代码的前提下增加了test1函数的运行时间,但是它改变了test1的调用方式,因此不是装饰器
def dec(fun):
    start_time = time.time()
    fun()                                                  #在这里test1运行了
    stop_time = time.time()
    print("The run time is %d" % (stop_time-start_time))

dec(test1)                                        #把test1函数当成一个实参传给dec函数,实际传过去的test1函数的内存地址
高阶函数2:不改变函数的调用方式
import time 

def test1( ):
    time.sleep(1)
    print("in the test1")

#这个函数不改变test1函数的调用方式
def dec(fun):
    return fun

test1 = dec(test1)
test1( )

3、嵌套函数

嵌套函数即在某函数A内定义一个新函数B,则B函数只能在A函数内被调用
def nesting():
    def bar():
        print("in the bar")
    bar()

nesting()
4、实现装饰器
4.1利用高阶函数的两个特性+嵌套函数实现装饰器
def dec(fun):
    def bar(*args,**kwargs):            #接收被装饰函数的参数,不定数量,如果没有参数则为空,不影响装饰器运行
        start_time = time.time()
        t = fun(*args,*kwargs)
        stop_time = time.time()
        print("The run time is %d" %(stop_time-start_time))
        return t                                   #返回被装饰函数的返回值
    return bar                                   #即dec函数返回的是bar函数的内存地址

                     
def test1():
    time.sleep(1)
    print("in the test1")
                     
def test2(name):
    time.sleep(1)
    print("in the test2")
    print("The name is %s" % name)
    return name


test1 = dec(test1)                #dec(test1)返回的是bar函数的内存地址
test1()                                   ##此时的test1( )其实是等于bar( )

test2 = dec(test2)              #dec(test2)返回的是bar函数的内存地址
k = test2("LBJ")                  #此时的test2("LBJ")其实是等于bar("LBJ")
print("k等于%s" % k )

--------------------/---------------------------------
test1 = dec(test1)   相当于在定义test1函数的上一行加上   @dec  
test2 = dec(test2)   相当于在定义test2函数的上一行加上   @dec         

@dec称为语法糖,也就是这样实现了装饰器的效果
4.2 带参数的装饰器
如果是装饰器本身也有参数需要传入,则可以再加一层嵌套,形成三层形式的嵌套函数,例子如下:
import time

def dec(x):
    print("X是%s" % x)
    def out(fun):
        def bar(*args,**kwargs):
            start_time = time.time()
            t = fun(*args,*kwargs)
            stop_time = time.time()
            print("The run time is %d" %(stop_time-start_time))
            return t
        return bar
    return out


@dec('King')
 def test1():
    time.sleep(1)
    print("in the test1")


@dec('HELLO')
def test2(name):
    time.sleep(1)
    print("in the test2")
    print("The name is %s" % name)
    return name


test1()
k = test2("LBJ")
print("k等于%s" % k )


这类装饰器的作用是可以根据传入装饰器的参数的不同用if语句做判断,对被装饰函数增加不同的功能
















猜你喜欢

转载自blog.csdn.net/a971956955/article/details/80766012