python中@property裝飾器的使用


python中@property裝飾器的使用

1、引出問題

在為一個類實例綁定屬性時,如果我們直接把屬性暴露出去,雖然寫起來很簡單,但是,沒辦法檢查參數,導致可以把成績隨便改,甚至類型錯誤都可以。

class Student(object):

    def __init__(self, score):
        self.score = score


if __name__ == '__main__':
    s = Student(100)
    print(s.score)
    s.score = 50
    print(s.score)
    s.score = 'abc'
    print(s.score)

------------------------------

>>> 100
>>> 50
>>> abc

2、初步改善

上述例子顯然不合邏輯,為了限制score的范圍,可以通過一個set_score()方法來設置成績,再通過一個get_score()方法來獲取成績,這樣,在set_score()方法里就可以檢查參數了。

class Student(object):

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer !')
        if value < 0 or value > 100:
            raise ValueError('score must between 0-100 !')
        self._score = value

    def get_score(self):
        return self._score


if __name__ == '__main__':
    s = Student()
    s.set_score(50)
    print(s.get_score())
    s.set_score('abc')

------------------------------

>>> 50
>>> Traceback (most recent call last):
  File "/Users/luyuze/projects/myflask/App/test.py", line 18, in <module>
    s.set_score('abc')
  File "/Users/luyuze/projects/myflask/App/test.py", line 6, in set_score
    raise ValueError('score must be an integer !')
ValueError: score must be an integer !

現在,對任意的Student實例進行操作,就不能隨心所欲的設置score了。

3、使用@property

上面的調用方法雖然已經可以實現相關功能,但是使用起來略顯復雜,設置和獲取屬性都需要通過調用方法來實現,沒有直接用屬性這么簡潔明了。

那么,有沒有既能檢查參數,又可以用類似屬性這樣簡單的方式來訪問類的變量呢?對於追求完美的python來說,這是必須做到的!

下面,我們就使用python內置的裝飾器@property來實現。

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer !')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 - 100 !')
        self._score = value


if __name__ == '__main__':
    s = Student()
    s.score = 50 # 實際轉化為s.set_score()
    print(s.score) # 實際轉化為s.get_score()
    s.score = 101

------------------------------

>>> 50
>>> Traceback (most recent call last):
  File "/Users/luyuze/projects/myflask/App/test.py", line 21, in <module>
    s.score = 101
  File "/Users/luyuze/projects/myflask/App/test.py", line 13, in score
    raise ValueError('score must between 0 - 100 !')
ValueError: score must between 0 - 100 !

4、解析@property

@property的實現比較復雜,我們先考察如何使用,把一個getter方法變成屬性,只需要加上@property就可以了,此時,@property本身又創建了另一個裝飾器@score.setter,負責把一個setter方法變成屬性賦值,於是,我們就擁有了如上例子中的屬性操作。

注意到這個神奇的@property,我們在對實例屬性操作的時候,就知道該屬性很可能不是直接暴露的,而是通過getter和setter方法來實現的。

我們還可以定義只讀屬性,只定義getter方法,不定義setter方法就是一個只讀屬性。

import datetime


class Student(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        if not isinstance(value, int):
            raise ValueError('birth must be an integer !')
        self._birth = value

    @property
    def age(self):
        return datetime.datetime.now().year - self._birth


if __name__ == '__main__':
    s = Student()
    s.birth = 1995
    print(s.age)
    s.age = 25

------------------------------

>>> 24
>>> Traceback (most recent call last):
  File "/Users/luyuze/projects/myflask/App/test.py", line 25, in <module>
    s.age = 25
AttributeError: can't set attribute

上面的birth是可讀寫屬性,而age就是一個只讀屬性,因為可以根據birth和當前年份計算出來。

5、總結

@property廣泛應用在類的定義中,可以讓調用者寫出簡短的代碼,同時保證對參數進行必要的檢查,這樣,程序運行時就減少了出錯的可能性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM