python之装饰器篇
一.基本裝飾器
基本裝飾器的作用:
在不改變?cè)瘮?shù)的基礎(chǔ)上, 通過裝飾器, 給原函數(shù)新增某些功能
實(shí)現(xiàn)方法:
在原函數(shù)上加
@裝飾器名字
其中@叫做語法糖
定義裝飾器
第一層函數(shù)傳入?yún)?shù)(用于傳入原函數(shù))
第二層使用原函數(shù)的同時(shí), 加入需要新增的功能
第一層函數(shù)要返回第二層函數(shù)名
整個(gè)函數(shù)形成閉包
import timedef runtime(func):def wrapper():start = time.time()for i in range(100):func()end = time.time()print("程序運(yùn)行時(shí)間為 {} ".format((end - start)/1000.0))return wrapper@runtime def hello():print("hello world")hello()?
? 二.三層裝飾器現(xiàn)在需要在裝飾器的基礎(chǔ)上, 調(diào)用 @裝飾器 的時(shí)候傳入?yún)?shù)
就需要在原有的裝飾器的基礎(chǔ)上, 在外層寫一個(gè)函數(shù), 從而又形成閉包的結(jié)構(gòu)
import timedef runtime(msg="默認(rèn)值"):def decorator(func):def wrapper():start = time.time()for i in range(100):func()end = time.time()print(msg)print("程序運(yùn)行時(shí)間為 {} ".format((end - start) / 1000.0))return wrapperreturn decorator@runtime("hello()") def hello():print("hello world")hello()?
三.完善參數(shù)傳遞
在之前的裝飾器中, 由于原函數(shù)可能存在不同種類的參數(shù), 可能有各種各樣的返回值, 所以要進(jìn)行一下兩點(diǎn)修改
1 將裝飾器實(shí)際執(zhí)行函數(shù)的參數(shù)設(shè)置為(*, **)的形式
2 改函數(shù)需要return 原函數(shù)
import timedef log(msg="默認(rèn)值"):def decorator(func):def wrapper(*args, **kwargs):print(func.__name__, msg)return func(*args, **kwargs)return wrapperreturn decorator@log("hello()") def hello():print("hello world")hello()?
轉(zhuǎn)載于:https://www.cnblogs.com/asaka/p/6700265.html
總結(jié)
以上是生活随笔為你收集整理的python之装饰器篇的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你说你精通CSS,真的吗?
- 下一篇: 20个必不可少的Python库