Python 函數和常用模組 - 裝飾器前奏
裝飾器
定義
本質是函數,用來裝飾其他函數,主要就是為了幫其他函數添加附加功能
原則
- 不能修改被裝飾的函數的源代碼
- 不能修改被裝飾的函數的調用方式
簡單示範一下,什麼是 裝飾器
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import time
# 寫一個裝飾器
def timmer(func):
def warpper(*args, **kwargs):
start_time = time.time()
func()
stop_time = time.time()
print('the func run time is {}'.format(stop_time - start_time))
return warpper
@timmer # 調用裝飾器
def hello():
time.sleep(3)
print('in the hello')
hello()
---------------執行結果---------------
in the hello
the func run time is 3.004323959350586
Process finished with exit code 0
實現裝飾器知識須知
- 函數就是
變量
- 高階函數
- 把一個函數名當做實際參數傳給另一個函數,
在不修改被裝飾函數源代碼的情況下,為它加上新的功能
。 - 返回值中包含函數名,
不修改函數的調用方式
- 返回值可以是『字符串、數字、列表、元組、函數名』
- 巢狀(嵌套)函數
高階函數 + 巢狀(嵌套)函數 => 裝飾器