python中@property的使用

來源:互聯網
上載者:User

標籤:core   使用   getter   限制   操作   ror   turn   error   __init__   

在綁定屬性時,如果我們將屬性直接暴露在外面,就可能導致屬性被任意修改,有時候這個是我們不希望看到的
如:設定學生的成績
class Student(object):    def __init__(self):        self.score = 0
#這個顯然不符合屬性的規範
#std = Student()
#std.score = 99999
#print std.score
#於是我們採用內部限制的方法來設定
 1 class Student2(object): 2     def __init__(self): 3         pass 4  5     def get_score(self): 6         return self._score 7  8     def set_score(self, value): 9         if not isinstance(value, int):10             raise ValueError(‘score must be an integer!‘)11         if value < 0 or value > 100:12             raise ValueError(‘score must between 0 ~ 100!‘)13         self._score = value14 15 16 std2 = Student2()17 std2.set_score(60)18 print std2.get_score() #6019 20 std2.set_score(99999)21 print std2.get_score()22 23 Traceback (most recent call last):24   File "/home/mywork/oldboy/practice/property.py", line 44, in <module>25     std2.set_score(99999)26   File "/home/mywork/oldboy/practice/property.py", line 35, in set_score27     raise ValueError(‘score must between 0 ~ 100!‘)28 ValueError: score must between 0 ~ 100!
#但是,上面的調用方法又略顯複雜,這就是需要應用@property
#他的本質就是把一個getter方法變成屬性
#此時,@property本身又建立了另一個裝飾器@score.setter,
#負責把一個setter方法變成屬性賦值,於是,我們就擁有一個可控的屬性操作:
看代碼:
 1 class Student3(object): 2  3     @property 4     def score(self): 5         return self._score 6  7     @score.setter 8     def score(self, value): 9         if not isinstance(value, int):10             raise ValueError(‘score must be an integer!‘)11         if value < 0 or value > 100:12             raise ValueError(‘score must between 0 ~ 100!‘)13         self._score = value14 15 std3 = Student3()16 std3.score = 9017 print std3.score #9018 std3.score = 9000 #直接設定時就報錯19 20 Traceback (most recent call last):21   File "/home/mywork/oldboy/practice/property.py", line 69, in <module>22     std3.score = 900023   File "/home/mywork/oldboy/practice/property.py", line 63, in score24     raise ValueError(‘score must between 0 ~ 100!‘)25 ValueError: score must between 0 ~ 100!

 

python中@property的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.