首页
/ 使用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库提供了灵活的方式来实现不同需求的只读属性,开发者可以根据具体场景选择最适合的方法。

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