python常用的装饰器有哪些_python基本装饰器
#基本代碼:
import time
def decoratorrunlog_args(logval):
print("logval is runing"+str(logval))
def decoratorrunlog(func):
print("outerlog is runing")
def inner(*args,**kwargs):
print("innerlog is runing")
stime = time.time()
time.sleep(1)
res = func(*args,**kwargs)
etime = time.time()
print(etime - stime)
print("innerlog is stoping")
return res
print("outerlog is stoping")
return inner
print("logval is stoping")
return decoratorrunlog
def decoratortuntime_args(timeval):
print("timeval is runing:"+str(timeval))
def decoratorruntime(func):
print("outer is runing")
def inner(*args,**kwargs):
print("inner is runing")
stime = time.time()
time.sleep(1)
res = func(*args,**kwargs)
etime = time.time()
print(etime - stime)
print("inner is stoping")
return res
print("outer is stoping")
return inner
print("timeval is stoping")
return decoratorruntime
@decoratorrunlog_args("argsonelog")
@decoratortuntime_args("argstwotime")
def funcone(pname):
print("this is a basic function")
return pname
res = funcone("lily")
print(res)
#執(zhí)行結(jié)果
logval is runingargsonelog
logval is stoping
timeval is runing:argstwotime
timeval is stoping
outer is runing
outer is stoping
outerlog is runing
outerlog is stoping
innerlog is runing
inner is runing
this is a basic function
1.000281810760498
inner is stoping
2.000582218170166
innerlog is stoping
lily
#圖示
#說(shuō)明:
圖中:1.1,1.2,2.1,2.2 中, "."之前的數(shù)字表示執(zhí)行的步驟,之后的數(shù)字表示多個(gè)裝飾器的數(shù)字標(biāo)識(shí);
#運(yùn)行順序
基本是按照代碼編寫(xiě)順序執(zhí)行
第一步:1.1、1.2: 執(zhí)行帶參數(shù)的裝飾器本身,
第二步:2.2、2.1:執(zhí)行裝飾器
第三步:3.1、3.2:執(zhí)行裝飾器內(nèi)部的閉包函數(shù)
第四步:func:執(zhí)行裝飾器裝飾的函數(shù)本身
第五步:5.2、5.1:執(zhí)行閉包中func后面的部分
裝飾器執(zhí)行的順序:按照其在所裝飾的函數(shù)中放置的順序來(lái)執(zhí)行。首先從最上面的裝飾器開(kāi)始按順序執(zhí)行到函數(shù)位置,然后在從函數(shù)位置向上執(zhí)行到最上面的裝飾器,再接著向下執(zhí)行,如此反復(fù)直到裝飾器最內(nèi)部的函數(shù)執(zhí)行到被裝飾的函數(shù)本身之后才開(kāi)始執(zhí)行被裝飾的函數(shù)。順序類(lèi)似于:↓↑↓↑
總結(jié)
以上是生活随笔為你收集整理的python常用的装饰器有哪些_python基本装饰器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 雪花算法生成数字id_全局唯一iD的生成
- 下一篇: python读取txt文件存储数组_py