成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

通過八個 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!

這個裝飾器將函數放在不同的線程中執行,并等待所有線程完成。

責任編輯:趙寧寧 來源: 小白PythonAI編程
相關推薦

2024-09-12 15:32:35

裝飾器Python

2024-03-08 08:00:00

Python開發裝飾器

2022-09-21 13:32:39

Python裝飾器

2024-05-21 10:40:09

開發前端裝飾器

2024-08-27 12:18:23

函數Python

2022-09-19 23:04:08

Python裝飾器語言

2022-02-11 09:00:00

技術債務數據工具

2010-02-01 17:50:32

Python裝飾器

2023-02-07 07:47:52

Python裝飾器函數

2024-05-13 18:33:08

SQL日期函數

2024-07-18 15:08:27

2025-01-06 12:00:00

Python函數內置函數

2010-11-09 14:18:41

2009-12-03 17:18:19

軟件路由器功能

2024-11-11 06:10:00

Python生成器迭代器

2021-06-01 07:19:58

Python函數裝飾器

2017-01-05 09:59:45

2012-10-29 11:01:17

2017-04-20 12:51:28

2023-02-27 09:08:10

IT文化步驟
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产成人福利在线 | 草樱av| 亚洲福利在线观看 | 国产一区三区视频 | 91国在线 | 午夜在线| 精品国产不卡一区二区三区 | 午夜三级视频 | 日本一二区视频 | 国产精品区一区二 | 国产成人av在线 | 一区二区三区亚洲 | 久久精品国产一区二区电影 | 99re在线视频 | 一区在线播放 | 福利一区视频 | 日韩精品二区 | 毛片99 | 久久精品一 | 一级毛片免费看 | 羞羞色视频 | 成人一区二区三区 | 一级a性色生活片久久毛片波多野 | www.色综合| 91视频精选 | 亚洲一区二区三区福利 | 欧美三级久久久 | 日一区二区 | 日韩电影中文字幕 | 欧美三级电影在线播放 | 国产精品日韩一区 | 亚洲在线一区二区 | 精品国产一区二区在线 | 久久久成人免费一区二区 | 91色网站 | 一区二区三区回区在观看免费视频 | 九九综合九九 | 久久久免费精品 | 久久久久国产精品一区 | 韩国久久精品 | 在线成人www免费观看视频 |