Day36-關於@property的使用小練習

    今天覆習到面向對象的裝飾器,廖雪峯的講解太膚淺了,不易理解。自己做出來一個小練習,試着理解方法變屬性:

class Screen(object):

    @property     # 相當於替代get方法,可以調用height
    def width(self):
        return self._width

    @width.setter  # 設置屬性
    def width(self, value):
        self._width = value

    @property  @ 替代get方法,可以調用height
    def height(self):
        return self.height

    @height.setter   # 設置屬性
    def height(self, value):
        self._height = value

    @property  # 可讀可調不可寫(傳參)的屬性
    def resolution(self):
        return self._width * self._height


def main():
    s = Screen()
    s.width = 1024
    s.height = 768
    print('resolution =', s.resolution)
    if s.resolution == 786432:
        print('測試通過!')
    else:
        print('測試失敗!')


if __name__ == '__main__':
    main()
    這個小練習倒是自己做完了,格式也明白。可是這個property和setter還是有點意猶未盡,理解得不清晰。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章