通過八個 Python 裝飾器理解高階函數
1. 什么是高階函數?
高階函數是指至少滿足以下條件之一的函數:
- 接受一個或多個函數作為參數。
- 返回一個函數。
裝飾器就是一種特殊的高階函數,用來修改其他函數的行為。
2. 為什么使用裝飾器?
裝飾器可以讓我們在不修改原始函數代碼的情況下,增加額外的功能。比如記錄日志、計時、緩存等。這樣不僅讓代碼更簡潔,也更容易維護。
3. 裝飾器的基本語法
裝飾器本質上是一個接受函數作為參數的函數,并返回一個新的函數。下面是一個簡單的裝飾器示例。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
輸出:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
4. 實戰案例六:參數驗證裝飾器
參數驗證裝飾器可以在執行函數之前驗證傳入參數的有效性。
def validate_params(*param_types):
def decorator(func):
def wrapper(*args, **kwargs):
if len(args) != len(param_types):
raise ValueError("Incorrect number of arguments")
for arg, param_type in zip(args, param_types):
if not isinstance(arg, param_type):
raise TypeError(f"Argument {arg} is not of type {param_type.__name__}")
return func(*args, **kwargs)
return wrapper
return decorator
@validate_params(int, int)
def multiply(x, y):
return x * y
print(multiply(3, 4)) # 正確
# print(multiply(3, "hello")) # 拋出 TypeError
輸出:
12
這個裝飾器會檢查傳入的參數類型是否符合預期。如果不符合,會拋出相應的異常。
5. 實戰案例七:限制調用次數裝飾器
限制調用次數裝飾器可以在一定時間內限制函數的調用次數。
import time
def limit_calls(max_calls, period):
def decorator(func):
call_times = []
def wrapper(*args, **kwargs):
current_time = time.time()
call_times.append(current_time)
while call_times and call_times[0] < current_time - period:
call_times.pop(0)
if len(call_times) > max_calls:
raise Exception("Too many calls in a short period of time")
return func(*args, **kwargs)
return wrapper
return decorator
@limit_calls(max_calls=2, period=5)
def process_request(data):
print(f"Processing request: {data}")
process_request("data1")
time.sleep(1)
process_request("data2")
time.sleep(1)
process_request("data3") # 拋出 Exception
輸出:
Processing request: data1
Processing request: data2
Too many calls in a short period of time
這個裝飾器限制了 process_request 函數在 5 秒內只能被調用兩次。如果超過這個限制,會拋出異常。
6. 實戰案例八:緩存裝飾器(自定義)
自定義緩存裝飾器可以根據特定需求實現緩存功能。
from functools import wraps
def custom_cache(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, frozenset(kwargs.items()))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@custom_cache
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(10):
print(fibonacci(i))
輸出:
0
1
1
2
3
5
8
13
21
34
這個裝飾器使用了一個字典 cache 來存儲函數的計算結果。如果相同的參數再次傳入,就直接從緩存中獲取結果。
7. 實戰案例九:異步裝飾器
異步裝飾器可以讓函數異步執行,提高程序的響應速度。
import asyncio
async def async_decorator(func):
async def wrapper(*args, **kwargs):
return await func(*args, **kwargs)
return wrapper
@async_decorator
async def download_file(url):
print(f"Downloading file from {url}")
await asyncio.sleep(2) # 模擬下載過程
print(f"File downloaded from {url}")
async def main():
await asyncio.gather(
download_file("http://example.com/file1"),
download_file("http://example.com/file2")
)
asyncio.run(main())
輸出:
Downloading file from http://example.com/file1
Downloading file from http://example.com/file2
File downloaded from http://example.com/file1
File downloaded from http://example.com/file2
這個裝飾器將函數轉換為異步函數,并允許并行執行多個任務。
8. 實戰案例十:多線程裝飾器
多線程裝飾器可以讓函數在多個線程中并發執行。
import threading
def thread_decorator(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
return thread
return wrapper
@thread_decorator
def print_message(message):
print(message)
print_message("Hello, world!")
print_message("Goodbye, world!")
# 等待所有線程完成
for thread in threading.enumerate():
if thread != threading.current_thread():
thread.join()
輸出(順序可能不同):
Hello, world!
Goodbye, world!
這個裝飾器將函數放在不同的線程中執行,并等待所有線程完成。