python装饰器

在Python中,装饰器可以简化代码、增加功能或者优化性能。下面是一些常见的装饰器及其用法:

1. @property

@property 是用来创建只读属性的装饰器。它把一个方法转换成属性的形式访问,可以让你对实例属性的获取进行更加详细的控制。

用法示例:

python 复制代码
class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @property
    def area(self):
        return 3.14159 * self._radius ** 2

c = Circle(4)
print(c.radius)  # 输出: 4
print(c.area)    # 输出: 50.26544

2. @staticmethod

@staticmethod 是用来表明一个方法是静态方法,它不需要表示一个类的实例或者类本身。

用法示例:

python 复制代码
class Math:
    @staticmethod
    def add(x, y):
        return x + y

print(Math.add(5, 7))  # 输出: 12

3. @classmethod

@classmethod 使得方法成为类方法,这意味着这个方法接收当前类作为第一个参数,而不是实例。

用法示例:

python 复制代码
class Person:
    species = 'Human'

    @classmethod
    def get_species(cls):
        return cls.species

print(Person.get_species())  # 输出: Human

4. @functools.lru_cache

来自functools模块,@lru_cache 是一个缓存装饰器,用于缓存最近使用的输入及其结果,从而加快连续调用的速度。

用法示例:

python 复制代码
from functools import lru_cache

@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(10))  # 输出: 55

5. @cached_property

@cached_property 是一个装饰器,用于将一个方法的返回值缓存为对象的属性。这意味着它只计算一次,然后将结果存储起来,用于后续的属性访问。

用法示例:

python 复制代码
from functools import cached_property

class Dataset:
    def __init__(self, data_source):
        self.data_source = data_source

    @cached_property
    def data(self):
        print("Loading data...")
        return load_data(self.data_source)  # 假设这是一个加载数据的函数

dataset = Dataset("data.csv")
print(dataset.data)  # 第一次访问,会加载数据
print(dataset.data)  # 后续访问,直接使用缓存的数据
相关推荐
用户8356290780513 小时前
使用 Python 操作 Word 内容控件
后端·python
码云骑士5 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
闵孚龙5 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
goldenrolan5 小时前
A公司物料替代测试系统 v1.7:从需求到 exe/apk 的 AI 辅助全链路实践
android·自动化测试·软件测试·python·ai
菜板春5 小时前
jupyter入门-手册-特征探索
python·jupyter
Metaphor6926 小时前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
极光代码工作室6 小时前
基于数据仓库的电商数据分析平台
大数据·hadoop·python·spark·数据可视化
开发小能手-roy6 小时前
StringBuilder vs StringBuffer:2024年还需要线程安全字符串吗?
开发语言·python·安全
AC赳赳老秦6 小时前
用 OpenClaw 搭建服务器故障应急响应系统,自动处理 80% 常见运维故障
android·运维·服务器·python·rxjava·deepseek·openclaw