首页
/ 使用attrs库实现只读属性的三种方法

使用attrs库实现只读属性的三种方法

2025-06-07 14:48:12作者:柏廷章Berta

在Python开发中,我们经常需要创建包含只读属性的数据类。attrs库作为Python中流行的数据类创建工具,提供了多种方式来实现这一需求。本文将介绍三种在attrs中实现只读属性的方法,每种方法都有其适用场景和优缺点。

方法一:使用property装饰器

最简单直接的方式是将属性定义为property:

@define
class LightModelInfo:
    wavelength: int = field(
        validator=validators.instance_of(int),
        metadata={"description": "Wavelength in nm."},
    )

    @property
    def wavecolor(self) -> str:
        return wavelength_to_hex(self.wavelength)

这种方法的特点是:

  • 每次访问属性时都会重新计算值
  • 属性值会随依赖项(wavelength)的变化而动态更新
  • 属性不会出现在attrs自动生成的repr中

方法二:使用property配合lru_cache

如果计算开销较大,可以结合functools.lru_cache实现缓存:

from functools import lru_cache

@define(hash=True)
class LightModelInfo:
    wavelength: int = field(
        validator=validators.instance_of(int),
        metadata={"description": "Wavelength in nm."},
    )

    @property
    @lru_cache
    def wavecolor(self) -> str:
        return wavelength_to_hex(self.wavelength)

这种方法的特点:

  • 首次访问时计算结果并缓存
  • 后续访问直接返回缓存值
  • 需要类是可哈希的(添加hash=True或自定义__hash__)
  • 同样不会出现在repr中

方法三:使用attrs的on_setattr机制

如果需要属性出现在repr中且只初始化一次,可以使用attrs的高级特性:

def read_only(self, attr, value):
    raise AttributeError(f"{attr.name} is read-only")

@define
class LightModelInfo:
    wavelength: int = field(
        validator=validators.instance_of(int),
        metadata={"description": "Wavelength in nm."},
    )
    wavecolor: str = field(
        init=False,
        on_setattr=read_only,
        metadata={"description": "Hexadecimal representation of the light color."},
    )
    
    @wavecolor.default
    def calculate_wavecolor(self):
        return wavelength_to_hex(self.wavelength)

这种方法的特点:

  • 属性会出现在repr中
  • 初始化后值固定不变
  • 即使依赖项(wavelength)变化,属性值也不会更新
  • 提供了完整的attrs功能支持

方法对比与选择建议

方法 动态更新 缓存 出现在repr 初始化后可变
property 不适用
property+lru_cache 不适用
on_setattr

选择建议:

  • 需要动态更新:使用方法一或二
  • 计算开销大:使用方法二
  • 需要完整attrs功能:使用方法三
  • 需要初始化后固定值:使用方法三

attrs库提供了灵活的方式来实现不同需求的只读属性,开发者可以根据具体场景选择最适合的方法。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
27
11
docsdocs
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
466
3.47 K
nop-entropynop-entropy
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
10
1
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
65
19
flutter_flutterflutter_flutter
暂无简介
Dart
715
172
giteagitea
喝着茶写代码!最易用的自托管一站式代码托管平台,包含Git托管,代码审查,团队协作,软件包和CI/CD。
Go
23
0
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
203
81
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.26 K
695
rainbondrainbond
无需学习 Kubernetes 的容器平台,在 Kubernetes 上构建、部署、组装和管理应用,无需 K8s 专业知识,全流程图形化管理
Go
15
1
apintoapinto
基于golang开发的网关。具有各种插件,可以自行扩展,即插即用。此外,它可以快速帮助企业管理API服务,提高API服务的稳定性和安全性。
Go
22
1