考虑以下:
@property
def name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name
Run Code Online (Sandbox Code Playgroud)
我是新手,但我认为缓存可能会被装入装饰器中.只有我找不到喜欢它的人;)
PS真正的计算不依赖于可变值
感谢来自这里的人们的帮助,我能够获得塔斯马尼亚骆驼拼图工作的代码.然而,它非常慢(我想.我不确定,因为这是我在Python中的第一个程序).在代码底部运行的示例需要很长时间才能在我的机器中解决:
dumrat@dumrat:~/programming/python$ time python camels.py
[['F', 'F', 'F', 'G', 'B', 'B', 'B'], ['F', 'F', 'G', 'F', 'B', 'B', 'B'],
['F', 'F', 'B', 'F', 'G', 'B', 'B'], ['F', 'F', 'B', 'F', 'B', 'G', 'B'],
['F', 'F', 'B', 'G', 'B', 'F', 'B'], ['F', 'G', 'B', 'F', 'B', 'F', 'B'],
['G', 'F', 'B', 'F', 'B', 'F', 'B'], ['B', 'F', 'G', 'F', 'B', 'F', 'B'],
['B', 'F', 'B', 'F', 'G', 'F', 'B'], ['B', 'F', 'B', 'F', 'B', 'F', 'G'],
['B', 'F', 'B', 'F', 'B', …Run Code Online (Sandbox Code Playgroud)