2017-02-23 21 views
-2

我試圖計算一次值(因爲它需要很長時間),然後存儲該值,以便它可以再次使用。
我知道types.MethodType,但我只想引用一個屬性,而不必調用它。重新分配@property方法python到對象

import types 

class stuff: 
    @property 
    def compute_once(self): 
    takes_long_time_to_calculate = 5 - 2 
    self.compute_once = takes_long_time_to_calculate 
    return takes_long_time_to_calculate 

instance = stuff() 

print(instance.compute_once) 
print(instance.compute_once) 

錯誤消息:

Traceback (most recent call last): 
    File "try.py", line 12, in <module> 
    print(instance.compute_once) 
    File "try.py", line 7, in compute_once 
    self.compute_once = takes_long_time_to_calculate 
AttributeError: can't set attribute 
+0

我意識到這不是很漂亮,但是idk –

回答

2

你只需要存儲在另一個屬性昂貴的計算結果。你可以用一個前導下劃線給它起一個名字來標記它爲私有的。這只是一個慣例,Python對這些屬性沒有做任何特別的事情,但是你的代碼的用戶會知道他們不應該直接介入它。 Python並沒有真正的私有屬性,相反它的哲學是「我們都在這裏同意大人」。見https://stackoverflow.com/a/70736/4014959

class Stuff: 
    def __init__(self): 
     self._compute_once = None 

    @property 
    def compute_once(self): 
     if self._compute_once is None: 
      print('Doing expensive calculation') 
      self._compute_once = 2 * 3 * 5 * 7 
     return self._compute_once 

instance = Stuff() 

print(instance.compute_once) 
print(instance.compute_once) 

輸出

Doing expensive calculation 
210 
210 

我們初始化._compute_onceNone且僅當._compute_onceNone進行昂貴的計算。我們可以通過將._compute_once重置爲None來隨時強制重新計算。

有關屬性如何工作的更多信息,請閱讀Python核心開發人員(和SO老手)Raymond Hettinger的優秀Descriptor HowTo Guide