日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python常用的装饰器有哪些_python基本装饰器

發布時間:2025/3/15 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)

#執行結果

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

#圖示

#說明:

圖中:1.1,1.2,2.1,2.2 中, "."之前的數字表示執行的步驟,之后的數字表示多個裝飾器的數字標識;

#運行順序

基本是按照代碼編寫順序執行

第一步:1.1、1.2: 執行帶參數的裝飾器本身,

第二步:2.2、2.1:執行裝飾器

第三步:3.1、3.2:執行裝飾器內部的閉包函數

第四步:func:執行裝飾器裝飾的函數本身

第五步:5.2、5.1:執行閉包中func后面的部分

裝飾器執行的順序:按照其在所裝飾的函數中放置的順序來執行。首先從最上面的裝飾器開始按順序執行到函數位置,然后在從函數位置向上執行到最上面的裝飾器,再接著向下執行,如此反復直到裝飾器最內部的函數執行到被裝飾的函數本身之后才開始執行被裝飾的函數。順序類似于:↓↑↓↑

總結

以上是生活随笔為你收集整理的python常用的装饰器有哪些_python基本装饰器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。