標籤: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的使用