python中的property屬性


1. 基本認識

property屬性可以用來給屬性添加約束,比如溫度屬性,我們不允許低於-273度;成績屬性,我們不允許0分以下等等。而且使用property屬性,將來修改約束條件的時候也很方便,可以在代碼的調用方式不變的情況下改變結果。

python中使用property屬性有兩種方法。使用@property裝飾器和使用property()函數。

我們通過廖雪峰官方網站的實例來對此加深認識。

2. @property裝飾器

@property裝飾器就是負責把一個方法變成屬性調用的。如下實例就可以通過s.score來獲得成績,並且對score賦值之前做出了數據檢查。

class Student(object):
    def __init__(self, score=0):
        self._score = score
    
    @property    
    def score(self):
        print("getting score")
        return self._score
    
    @score.setter
    def score(self, value):
        print("setting score")
        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(60)
s.score
print("=====================")
s.score = 88
s.score

3. property()函數

python中關於property()函數的介紹如下,在jupyter notebook中輸入property??,即可查看用法:

從幫助中可以看出,property()函數可以接收4個參數,第一個參數對應獲取,第二個參數對應設置,第三個參數對應刪除,第四個參數對應注釋,寫法如下:

class Student(object):
    def __init__(self, score=0):
        self._score = score
       
    def get_score(self):
        print("getting score")
        return self._score
    
    def set_score(self, value):
        print("setting score")
        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 del_score(self):
        print("delete score")
        del self._score

    score = property(get_score, set_score, del_score)

s = Student(60)
print(s.score)
print("=====================")
s.score = 88
print(s.score)
print("=====================")
del s.score

參考鏈接:

[1] https://www.liaoxuefeng.com/wiki/1016959663602400/1017502538658208

[2] https://www.programiz.com/python-programming/property

[3] https://www.geeksforgeeks.org/python-property-function/


免責聲明!

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



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