Python中的装饰器是一种强大的功能,用于在不修改原始函数或类代码的情况下,动态地修改或增强函数或类的行为。以下是一些常用的Python装饰器:
@property
用于将方法变成属性调用。
```python
class DataSet(object):
@property
def method_with_property(self):
return 15
def method_without_property(self):
return 15
l = DataSet()
print(l.method_with_property) 输出:15
print(l.method_without_property()) 输出:15
@abstractmethod
用于定义抽象基类中的抽象方法。
```python
from abc import ABC, abstractmethod
class Foo(ABC):
@abstractmethod
def fun(self):
pass
class SubFoo(Foo):
def fun(self):
print('fun in SubFoo')
a = SubFoo()
a.fun() 输出:fun in SubFoo
@staticmethod
用于定义静态方法,静态方法不需要实例化类即可调用。
```python
class MyClass:
@staticmethod
def static_method():
return "This is a static method."
print(MyClass.static_method()) 输出:This is a static method.
@classmethod
用于定义类方法,类方法接收类本身作为第一个参数。
```python
class MyClass:
@classmethod
def class_method(cls):
return "This is a class method."
print(MyClass.class_method()) 输出:This is a class method.
@timer
用于测量函数的执行时间。
```python
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, kwargs):
start = time.perf_counter()
result = func(*args, kwargs)
end = time.perf_counter()
print(f'执行 {func.__name__} 函数共耗时 {end - start:.6f} 秒。')
return result
return wrapper
@timer
def my_data_processing_function():
Your data processing code here
@memoize
用于缓存函数的结果,避免重复计算。
@validate_input
用于验证函数的输入参数。
@log_results
用于记录函数的输出结果。
@suppress_errors
用于优雅地处理异常。
这些装饰器可以单独使用,也可以组合使用,以提供更复杂的功能。装饰器使得代码更加简洁、清晰,并提高了代码的重用性和可维护性