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)  # 后续访问,直接使用缓存的数据
相关推荐
虎虎(_ _)。゜zzZ1 小时前
关于字典中的解包问题
python
全栈弄潮儿²⁰²⁴1 小时前
Python实战第2期: 变量与数据类型
python·变量·数据类型·python实战
程序员yu2 小时前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
鬼手点金2 小时前
opencode组件详解-安装方式
人工智能·python·优化器·分析器·nanogpt
Bruce_Liuxiaowei2 小时前
Python 字典默认值完全指南:从 KeyError 到 defaultdict
开发语言·数据结构·python·字典
数据杂坛2 小时前
【Python程序开发系列】一文搞清楚Gunicorn以及和Nginx的区别
python·nginx·gunicorn
zjh9005302 小时前
Visual C++ 2010 安装使用完整包:高手秘籍
python
Allen_LVyingbo3 小时前
信息化部门在AI时代的编程转移路径分析(上)
人工智能·python·算法·健康医疗·数据库开发·时序数据库·数据库架构
用户0332126663673 小时前
Python 实现 Word/TXT 互转:附完整代码
python
常山云栈3 小时前
Anaconda和uv的区别是什么?
python·anaconda·uv