【发布时间】:2021-11-21 12:36:51
【问题描述】:
我有一个只接受一个输入参数的类。然后,该值将用于计算许多属性(以下示例中只有一个)。如果我只想在调用属性时才进行计算,那么什么是 Pythonic 方式。另外,结果应该被缓存,attr2不能从类外设置。
class LazyInit:
def __init__(self, val):
self.attr1 = val
self.attr2 = self.compute_attr2()
def compute_attr2(self):
return self.attr1 * 2 # potentially costly computation
if __name__ == "__main__":
obj = LazyInit(10)
# actual computation should take place when calling the attribute
print(obj.attr2)
【问题讨论】:
-
定义一个 getter (
propertydocs)。
标签: python lazy-initialization