【问题标题】:Reassign @property method python to object将@property方法python重新分配给对象
【发布时间】:2017-07-13 23:25:54
【问题描述】:

我正在尝试计算一次值(因为它需要很长时间)然后存储该值以便再次使用它。
我知道 types.MethodType 但我只想引用一个属性而不必调用它。

import types

class stuff:
  @property
  def compute_once(self):
    takes_long_time_to_calculate = 5 - 2
    self.compute_once = takes_long_time_to_calculate
    return takes_long_time_to_calculate

instance = stuff()

print(instance.compute_once)
print(instance.compute_once)

错误信息:

Traceback (most recent call last):
  File "try.py", line 12, in <module>
    print(instance.compute_once)
  File "try.py", line 7, in compute_once
    self.compute_once = takes_long_time_to_calculate
AttributeError: can't set attribute

【问题讨论】:

  • 我意识到这不是很漂亮,但 idk

标签: python python-3.x properties


【解决方案1】:

您只需要将昂贵计算的结果存储在另一个属性中。您可以通过给它一个带有单个前导下划线的名称来将其标记为私有。虽然这只是一个约定,Python 并没有对这些属性做任何特别的事情,但是你的代码的用户会知道他们不应该直接干预它。 Python 并没有真正的私有属性,而是具有“我们在这里都是成年人”的理念。见https://stackoverflow.com/a/70736/4014959

class Stuff:
    def __init__(self):
        self._compute_once = None

    @property
    def compute_once(self):
        if self._compute_once is None:
            print('Doing expensive calculation')
            self._compute_once = 2 * 3 * 5 * 7
        return self._compute_once

instance = Stuff()

print(instance.compute_once)
print(instance.compute_once)

输出

Doing expensive calculation
210
210

我们将._compute_once 初始化为None,并且仅当._compute_once 为None 时才执行昂贵的计算。我们可以随时通过将._compute_once重置为None来强制重新计算。

有关属性如何工作的更多信息,请阅读 Python 核心开发人员(也是 SO 老手)Raymond Hettinger 撰写的出色的 Descriptor HowTo Guide。

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 2012-07-13
    • 2021-05-12
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多