Python 装饰器

一、装饰器:

  1、定义:本质是函数(装饰其它函数),为其它函数添加附加功能

  2、原则:a):不能修改被函数的源代码。

        b):不能修改被装饰的函数的调用方式。

  3、实现装饰器知识储备:

    a):函数即"变量"

    b):高阶函数

1、把一个函数名当做一个实参传给另外一个函数(在修改原代码的情况下为其附件新的功能)     

#高阶函数的例字
import time #调用系统模块
def whitle():   #原函数
    time.sleep(3)   #延迟3秒运行
    print("in the white")   #模拟输出代码

def black(wb):  #装饰器,装饰whitle 在不改变原代码的情况下附加功能!
    start_time = time.time()
    wb()
    stop_time = time.time()
    print("wb run time%s"%(stop_time-start_time))   #统计whitle的运行时间。
black(whitle)   #把whitle函数名 实参的方式把内存地址传给了 black 注:不能以 black(whitle())进行实参进行传
#运行结果
in the white
wb run time3.0009474754333496

Process finished with exit code 0


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

import time
def whitle():   #原函数
    time.sleep(3)
    print("in the white")
def black(run):
    print(run)
    return run
black(whitle) #把函数名实参传给
whitle = (black(whitle)) #重新给函数体分配门牌号,不更改函数的调用方式。
whitle()

#运行结果
<function whitle at 0x0000021EA58FE268>
<function whitle at 0x0000021EA58FE268>
in the white

 

c):嵌套函数

 

#嵌套函数举列
def test1():
    def test2():
        pass
def timer(ca): #timer(date)   date = ca
    def test(*args,**kwargs):
        start_time = time.time()
        ca(*args,**kwargs)
        stop_stop = time.time()
        print("The run Date Time \033[31;1m%s\033[1m"%(start_time-stop_stop))
    return test

@timer
def data1():
    time.sleep(1)
    print("This Date 1")
#date1()
@timer #data = timer(date)
def data2(name,age):
    time.sleep(1)
    print("Data:",name,"age:",age)
data2("Byron",21)  #高价函数 + 嵌套函数  = 装饰器

 举例:论坛前期为了吸引更多的人浏览,并未设置账号密码认证登录浏览,现要求除首而index不进行认证登录,其它模块需要认证登录。

user = "byron" #1
paswd = "abc123"#2
def auth(auth_type):   #--5  --12
    #print("auth_type:",auth_type)
    def out_wrap(func): # --6  --8 --13 --15
        #print("auth_type:",func)
        def wrapter(*args, **kwargs): #--9 --16 --22 --31
            username = input("Plese Enter Username:").strip() #--23 --32
            password = input("Plese Enter Password:").strip()#--24 --33
            if auth_type == "local":
                if user == username and paswd == password: #--25
                    print("\033[32;1mWele Com!\033[0m") #--26
                    func(*args, **kwargs) #--28
                else:
                    print("\033[31;1mPlease you user or password Error!!!\033[0m")
            elif auth_type == "ldap": #--34
                print("我不会啊!!!") #--35
        return wrapter  #--10 --17
    return out_wrap     # --7 --14
def index():#--3 --19
    print("Well com index") #--20
@auth(auth_type = "local") # home = wrapter #--4  --29 采用本地认证
def home():
    print("Well com home") #--30
@auth(auth_type = "ldap")  #--11  采用远端服务器认证
def bbs():
    print("Well com bbs")
index() #--18
home() #--21
bbs()

 

posted @ 2017-10-10 00:28  Byron-He  阅读(181)  评论(0编辑  收藏  举报