python 中的计算静态 属性

Computed static property in python

是否可以在 class 上设置一个静态 属性,这将被计算为一次性。这个想法是能够像这样做到:

class Foo:
    static_prop = Foo.one_off_static_method()

    @staticmethod
    def one_off_static_method():
        return 'bar'

我也想过用__new__

Class Foo:
    def __new__(cls):
         cls.static_prop = ... do everything here

虽然不确定这意味着什么。

在实际创建class之前,one_off_static_method只是一个常规函数。它需要在您尝试调用它之前定义,因为您想在 class 语句正在执行时调用它。完成后,您可以简单地删除它。

class Foo:
    def _one_off_static_method():
        return 'bar'

    static_prop = _one_off_static_method()
    del _one_off_static_method

如果您希望它在 class 定义时计算,请参阅 - 尽管我建议只使用模块级函数。

如果您希望对每个实例进行延迟评估,那么您可能会对 functools.cached_property.

感兴趣
>>> from random import random
>>> from functools import cached_property
>>> class Foo(object):
...     @cached_property
...     def one_off_thing(self):
...         print("computing...")
...         return random()
...     
>>> foo = Foo()
>>> foo.one_off_thing
computing...
0.5804382038855782
>>> foo.one_off_thing
0.5804382038855782

注意: stdlib functools.cached_property 需要 Python 3.8+,对于 Python < 3.8 你可以 pip install cached_property.

给你,我为你做了一个小描述:-)

访问属性后,将对其进行计算和缓存。

class CachedStaticProperty:
    """Works like @property and @staticmethod combined"""

    def __init__(self, func):
        self.func = func

    def __get__(self, inst, owner):
        result = self.func()
        setattr(owner, self.func.__name__, result)
        return result

它的工作方式相当简单:

  1. 使用装饰器语法后,我在内部保存了函数。
  2. 访问后,我调用该函数并将值设置为与原始函数同名的 class 值。

仅此而已。简单高效。

从 Python 3.8 开始,cached_property 装饰器将包含在 Python builtin/core functools 库中。

https://docs.python.org/dev/library/functools.html?highlight=s#functools.cached_property

本站其他问题也有类似答案。一些亮点是可以做到的

@property
@functools.lru_cache(1)

(都是 Python 内置函数)以获得类似的效果。并且一些 Web 服务器库(如 Flask 或 Werkzeug)已经包含了它们自己的 cached_property 装饰器实现。

当然还有其他方法(如该问题的其他答案和其他问题的答案中所述)可以创建自己的自定义缓存 属性 装饰器。

python: are property fields being cached automatically?
Is there a decorator to simply cache function return values?