首页 > 解决方案 > AttributeError:“cached_property”对象没有属性“setter”

问题描述

我正在使用 functools.cached_property 来记忆一些功能。

但它似乎不支持二传手。

例如

class User
  @cached_property
  def name(self):
    return self._name

  @name.setter
  def name(self, val):
    self._name = val

但是在导入时我遇到了AttributeError: 'cached_property' object has no attribute 'setter'

标签: python

解决方案


@cached_property 专为不可变值而设计。你不能指望这个装饰器会模仿标准属性的所有特性。在 python 文档中,您可以找到:“cached_property() 的机制与 property() 有所不同。除非定义了 setter,否则常规属性会阻止属性写入。相反,cached_property 允许写入。”


推荐阅读