Python中的装饰器是一种强大的功能,用于在不修改原始函数或类代码的情况下,动态地修改或增强函数或类的行为。以下是一些常用的Python装饰器:
@property
用于将方法变成属性调用。
class DataSet(object):@propertydef method_with_property(self):return 15def method_without_property(self):return 15l = DataSet()print(l.method_with_property) 输出:15print(l.method_without_property()) 输出:15
@abstractmethod
用于定义抽象基类中的抽象方法。
from abc import ABC, abstractmethodclass Foo(ABC):@abstractmethoddef fun(self):passclass SubFoo(Foo):def fun(self):print('fun in SubFoo')a = SubFoo()a.fun() 输出:fun in SubFoo
@staticmethod
用于定义静态方法,静态方法不需要实例化类即可调用。
class MyClass:@staticmethoddef static_method():return "This is a static method."print(MyClass.static_method()) 输出:This is a static method.
@classmethod

用于定义类方法,类方法接收类本身作为第一个参数。
class MyClass:@classmethoddef class_method(cls):return "This is a class method."print(MyClass.class_method()) 输出:This is a class method.
@timer
用于测量函数的执行时间。
import timefrom functools import wrapsdef 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 resultreturn wrapper@timerdef my_data_processing_function():Your data processing code here```@memoize用于缓存函数的结果,避免重复计算。@validate_input用于验证函数的输入参数。@log_results用于记录函数的输出结果。@suppress_errors用于优雅地处理异常。这些装饰器可以单独使用,也可以组合使用,以提供更复杂的功能。装饰器使得代码更加简洁、清晰,并提高了代码的重用性和可维护性
