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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 笔记:装饰器

發(fā)布時間:2025/4/5 python 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 笔记:装饰器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1 裝飾器介紹

? ? ? ? 如果有一批函數(shù)都是需要前置或者后置的工作,那么我們可以統(tǒng)一使用裝飾器進行修飾。

??

1.1 不用裝飾器的版本? ?

def decorator(fn, name):print("I'm in", name) return fn(name)def outer_fn(name):print("I'm out of",name)decorator(outer_fn,'China')''' I'm in China I'm out of China '''

? ?這里相當(dāng)于把outer_fn這個函數(shù)作為參數(shù)傳入decorator中。

? ? decorator 函數(shù)會先執(zhí)行【? print("I'm in", name)? ? 】這一條語句

然后執(zhí)行 【? fn(name)? ?】,也就是【? outer_fn(name)? ?】

1.2 使用裝飾器

????????我們使用裝飾器有一個特別的寫法,就是在你要修飾(嵌套)的?outer_fn?上面寫上?@decorator。

???@?后面就是你定義的那個裝飾器 function 的名字。 比如這里我用的是?def decorator()?那么?@?后面就是?decorator?這個名字了。

????????寓意著,我要把?decorator?這個 function 套在?outer_fn?外面。

def decorator(fn):def wrapper(name):print("I'm in", name) return fn(name)return wrapper@decorator def outer_fn(name):print("I'm out of",name)outer_fn('China')''' I'm in China I'm out of China '''

相當(dāng)于執(zhí)行了

(1)decorator(outer_fn)

(2)在decorator里面執(zhí)行了 wrapper("China") ,先 【print("I'm in", name)? 】,再【fn(name)】,即【print("I'm out of",name)】

當(dāng)然,裝飾器還可以在要裝飾的函數(shù)后面執(zhí)行一些操作

def decorator(fn):def wrapper(name):print("I'm in", name) f=fn(name)print("I'm also in", name)return freturn wrapper@decorator def outer_fn(name):print("I'm out of",name)outer_fn('China')''' I'm in China I'm out of China I'm also in China '''

參考資料:

套娃的裝飾器 - 交互式學(xué)Python | 莫煩Python (mofanpy.com)

總結(jié)

以上是生活随笔為你收集整理的python 笔记:装饰器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。