我有一組非常大且昂貴的數組計算,並且在任何給定的運行中,我的代碼並不需要全部數組。我想使他們的聲明可選,但最好不必重寫我的整個代碼。python懶惰變量?或者延遲昂貴的計算
的現在是怎麼例子:
x = function_that_generates_huge_array_slowly(0)
y = function_that_generates_huge_array_slowly(1)
的想什麼,我做的例子:
x = lambda: function_that_generates_huge_array_slowly(0)
y = lambda: function_that_generates_huge_array_slowly(1)
z = x * 5 # this doesn't work because lambda is a function
# is there something that would make this line behave like
# z = x() * 5?
g = x * 6
雖然使用上述拉姆達達到期望的效果之一 - 的計算數組被延遲直到需要 - 如果多次使用變量「x」,它必須每次計算。我只想計算一次。
編輯: 經過一些額外的搜索,看起來有可能做到我想要的(大約)在一個類中使用「懶」屬性(例如http://code.activestate.com/recipes/131495-lazy-attributes/)。我不認爲有什麼辦法可以做一些類似的事情,而不需要另外上課?
EDIT2:我想實現的一些解決方案,但我到一個問題,運行,因爲我不明白之間的差別:
class sample(object):
def __init__(self):
class one(object):
def __get__(self, obj, type=None):
print "computing ..."
obj.one = 1
return 1
self.one = one()
和
class sample(object):
class one(object):
def __get__(self, obj, type=None):
print "computing ... "
obj.one = 1
return 1
one = one()
我想這些是我正在尋找的一些變化,因爲昂貴的變量是打算成爲一個類的一部分。
http://stackoverflow.com/questions/5078726/setting-a-property-inside-a-python-method是我試圖做的懶惰更有用的實現 – keflavich