1. 程式人生 > >Python學習(十三)--@property和property函數

Python學習(十三)--@property和property函數

span sin .com pre rac turn () 裝飾器 轉化

  • @property
@property裝飾器可以把一個方法變成屬性調用。 舉一個例子,對學生成績進行設置和查詢。通過set_score來設置成績,get_score來獲取成績。這樣的不方便之處就是不像直接用屬性那麽方便。
class Student(object):
 
    def get_score(self):
        return self._score
 
    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
然後通過@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 >>> s = Student() >>> s.score = 60 #
OK,實際轉化為s.set_score(60) >>> s.score # OK,實際轉化為s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
把一個getter方法變成屬性,只需要加上@property。@property本身又創建了另外一個裝飾器@score.setter,把一個setter方法變成屬性賦值。
  • property函數
property函數的原理和@property很相似,它有四個參數。 property(fget=None, fset=None, fdel=None, doc=None)
class Student(object):
 
    def get_score(self):
        return self._score
 
    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
 
    score = property(fget=get_score, fset=set_score)
 
>>> s = Student()
>>> s.score = 60 # OK,實際轉化為s.set_score(60)
>>> s.score # OK,實際轉化為s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!
參考: https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820062641f3bcc60a4b164f8d91df476445697b9e000

Python學習(十三)--@property和property函數