對 python 中 @property 和計算屬性的一些思考
阿新 • • 發佈:2022-03-08
前言
python 中提供了 @property
裝飾器,可以將一個成員函式變為成員變數來訪問,之前只是覺得這東西應該就只是為了 setter
和 getter
而存在的,但是學了 Vue 的計算屬性後對這個裝飾器有了新的見解。
計算屬性
在 Vue 中提供了計算屬性 computed
,避免在模板中寫出很長的表示式。仔細想想,用了 @property
裝飾器的方法不就是計算屬性的 get()
嗎,然後 @property.setter
不就是 set()
嗎?有了 get()
之後,當一個變數發生變化時,計算屬性也隨之發生變化,這樣在更新變數時沒必要手動在程式碼中更新計算屬性的值,程式碼看起來就更加簡潔了。比如,有以下程式碼:
class ImageViewer: def __init__(self): self.imagePaths = ['キラキラ.png', '戀をしたのは.png'] self.index = 0 def next(self): if self.index >= len(self.imagePaths)-1: return self.index += 1 def previous(self): if self.index <= 0 return self.index -= 1 @property def imagePath(self): return self.imagePaths[self.index]
有了 @property
之後,每次訪問到的 imagePath
都會是最新的,沒必要在 next()
方法和 previous()
中再寫一行更新 imagePath
的程式碼,我們只需維護好 index
即可,以上~