溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

初攝裝飾器

發(fā)布時(shí)間:2020-07-20 17:50:35 來源:網(wǎng)絡(luò) 閱讀:350 作者:v_fanyunxiao 欄目:開發(fā)技術(shù)

一、理論知識(shí):

      定義:裝飾器本身是函數(shù),就是為了為其他函數(shù)添加附加功能。

    原則:

        1、不能修改被修飾函數(shù)的源代碼

        2、不能修改被修飾函數(shù)的調(diào)用方式

    裝飾器知識(shí)必備:

        1、函數(shù)即“變量”

        2、高階函數(shù)

                a:把一個(gè)函數(shù)名作為實(shí)參傳給另外一個(gè)函數(shù)

                b:返回值中包含函數(shù)值

        3、嵌套函數(shù)

高階函數(shù)+嵌套函數(shù)=》裝飾器


二、低潮版

import time
def timmer(func):
def bar(*args,**kwargs):#*args,**kwargs:表示非固定參數(shù)
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
print ('the func run time %s'%(stop_time-start_time))
return bar#只是返回了內(nèi)存地址,并沒有運(yùn)行bar()函數(shù)
@timmer#調(diào)用裝飾器timmer。相當(dāng)于:test1=timmer(test1)
def test1():#由于返回bar()的地址,所以test1=timmer(test1)=bar
time.sleep(3)
print ('in the test1')
@timmer
def test2(name):
print ('in the test2',name)
#test1 = timmer(test1)#把返回的bar()函數(shù)內(nèi)存地址賦值給test1
test1()
test2(2)

三、高潮版

    當(dāng)被修飾函數(shù)中出現(xiàn)返回值(return 'from home')

user,passwd= 'peter','123qwe'
def auth(auth_type):
print ('auth_type:',auth_type)
def outer(func):
def warpper(*args,**kwargs):
print ('warpper:',*args,**kwargs)
username = input ('Username:').strip()
password = input ('Password:').strip()
if (user==username and passwd ==password):
print ('\033[32;1mUser has passed authentication\033[0m')
te=func(*args,**kwargs)#相當(dāng)于執(zhí)行home(*args,**kwargs)
print ('----------')
return te
else:
exit('\033[31;1mInvalid username or password\033[0m')
return warpper
return outer
def index():
print ('welcome to index page')
@auth(auth_type='local')
def home(name):
print ('welcome to home page',name )
return 'from home'
@auth(auth_type='lodap')
def bbs():
print ('welcome to bbs page')
index()
print (home(2))
bbs()

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI