Python裝飾器實用總結

十年開發一朝靈 2024-06-10 14:13:51

Python裝飾器是一種非常有用的編程特性,它可以讓我們在不修改原始函數代碼的情況下,爲函數添加額外的功能。裝飾器通常用于日志記錄、性能測試、事務處理、緩存等場景。

以下是一些關于Python裝飾器的實用總結和技巧:

1. 基礎裝飾器

裝飾器是一個函數,它接受一個函數作爲參數,並返回一個新的函數。使用@符號來應用裝飾器,將其放在要裝飾的函數前面。def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper@my_decoratordef say_hello(name): return f"Hello, {name}!"print(say_hello("World"))

2. 帶參數的裝飾器

裝飾器也可以接受參數,這種裝飾器通常需要兩層嵌套的函數。裝飾器的參數可以在裝飾器函數內部使用。def decorator_with_args(decorator_arg1, decorator_arg2): def decorator(func): def wrapper(*args, **kwargs): print(f"Something is happening before the function {func.__name__} is called.") result = func(*args, **kwargs) print(f"Something is happening after the function {func.__name__} is called.") return result return wrapper return decorator@decorator_with_args("arg1", "arg2")def say_hello(name): return f"Hello, {name}!"print(say_hello("World"))

3. 類裝飾器

裝飾器不僅可以是函數,還可以是類。類裝飾器通常需要實現__call__方法。類裝飾器接受一個函數作爲參數,並將其保存爲一個實例變量。class DecoratorClass: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("Something is happening before the function is called.") result = self.func(*args, **kwargs) print("Something is happening after the function is called.") return result@DecoratorClassdef say_hello(name): return f"Hello, {name}!"print(say_hello("World"))

4. 裝飾器的嵌套

Python支持裝飾器的嵌套,即一個函數可以有多個裝飾器。裝飾器的執行順序是從左到右。def decorator1(func): def wrapper(*args, **kwargs): print("Decorator 1 before") result = func(*args, **kwargs) print("Decorator 1 after") return result return wrapperdef decorator2(func): def wrapper(*args, **kwargs): print("Decorator 2 before") result = func(*args, **kwargs) print("Decorator 2 after") return result return wrapper@decorator1@decorator2def say_hello(name): return f"Hello, {name}!"print(say_hello("World"))

5. 裝飾器的應用場景

裝飾器通常用于添加日志記錄、性能測試、事務處理、緩存等功能。裝飾器可以提高代碼的可讀性和可維護性,因爲它們將額外的功能與原始函數分離。

6. 裝飾器的限制

裝飾器不能用于修改函數的名稱、參數或返回類型。裝飾器不能用于修改函數的代碼,除非使用類裝飾器。

裝飾器是Python中一種非常有用的編程特性,它可以讓我們在不修改原始函數代碼的情況下,爲函數添加額外的功能。在實際編程中,根據具體需求選擇合適的裝飾器,可以提高代碼的效率和質量。

0 阅读:1

十年開發一朝靈

簡介:感謝大家的關注