是否可以在一个类上拥有一个静态属性,该属性将被计算为一次性的。这个想法是能够像这样做到:
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/