python - python中的计算静态属性

标签 python static-methods

是否可以在一个类上拥有一个静态属性,该属性将被计算为一次性的。这个想法是能够像这样做到:

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

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

最佳答案

如果您希望它在类定义时计算,请参阅 chepner's answer - 虽然我建议只使用模块级函数。

如果您希望对每个实例进行延迟评估,那么您可能会对 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 .

关于python - python中的计算静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498891/

相关文章:

Java按钮事件调用另一个类中的方法

java - 返回内部类的静态方法

python - 为什么 SIP 和 PyQt4 不能相处

Python - 获取全局范围内对象的所有变量名

python - 使用 python 使用 gtk 3 构建 gtkbuilder 文件

python - 使用文件浏览器选择文件并将路径存储在 python 脚本中

python - tf.layers.conv2d和tf.contrib.slim.conv2d之间的区别

Python访问数据类default_factory字段而不实例化它

c++ - 具有静态(内联)方法的从未实例化类的基类

python - 静态方法和继承设计