Python之装饰器

Python 高阶函数:

    1.把一个函数名作为实参传递给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

    2.返回值中包含函数名(不修改函数的调用方式)

def test1():
    print("in the test1")

def test2(func): #接收函数名
    func()
    print("in the test2")
    return func  #返回函数内存地址

def test3():
    str = test2(test1)  #函数名test1 作为实参传递给函数 test2,并接收test1的 内存地址赋值给str
    print(str)
    print("in the test3")
    
test3()


Python 嵌套函数:

    在函数当中再定义函数。

def test1():
    pirnt("in the test1")
    def test2(): 
        print("in the test2")


高阶函数 +  嵌套函数 => 装饰器

    装饰器,在不修改源代码的基础上新增功能,并在不改变调用方式的前提下,实现功能添加,代码实现如下:

import time
def timer(func):
    def deco(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        stop_time = time.time()
        print("the func run time %s"% (stop_time-start_time))
    return deco

@timer #test1 = timer(test1)
def test1():
    time.sleep(1)
    print("in the test1")

@timer
def test2(name):
    time.sleep(1)
    print("name: ", name)

#test1 = timer(test1) #获取的deco的内存地址,所以执行test1(),实际上就是执行deco()
test1()  #deco()

# @timer 分解步骤如下
test2 = timer(test2) # 把deco的内存地址给了test2,所以执行test2(),实际上就是执行deco()
print("test2: ", test2)
test2("lilei")  #deco("lilie")
import time

username = "alex"
password = "abc123"
def auth(mode):
    def out_wrapper(func):
        def wrapper(*args, **kwargs):
            if mode == "local":
                start_time = time.time()
                rec =func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s"% (stop_time-start_time))
                return rec
            elif mode == "ldap":
                print("in the ldap")
                start_time = time.time()
                rec = func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s" % (stop_time - start_time))
                return rec
        return wrapper
    return out_wrapper


def index():
    print("Welcome in the index page")

@auth(mode="local") #  home=wrapper()
def home(name):
    print("in the home", name)
    return "from home"

#@auth(mode="ldap")
def bbs():
    print("in the bbs")

index()
home("alex")

# @auth(mode="ldap") 分解步骤如下
#out_wrapper = auth(mode="ldap")  # 把 out_wrapper 内存地址给了 out_wrapper
# print("aa:", out_wrapper)
#bbs = out_wrapper(bbs)  # 把 wapper 的内存地址给了bbs,所以执行bbs(),实际上就是执行wapper(),
bbs = auth(mode="ldap")(bbs)  #两步整合的结果: bbs = auth(mode="ldap")(bbs)
print("bbs:", bbs)
bbs()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章