python property()函數

描述

property() 函數的作用是在新式類中返回屬性值。大概意思就是讓方法變成一個屬性

語法

以下是 property() 方法的語法:

class property([fget[, fset[, fdel[, doc]]]])

參數

  • fget -- 獲取屬性值的函數
  • fset -- 設置屬性值的函數
  • fdel -- 刪除屬性值函數
  • doc -- 屬性描述信息

返回值

返回新式類屬性。

實例

 

 1 #! /usr/bin/python3
 2 # -*- coding:UTF-8 -*-
 3 
 4 class A(object):
 5     def __init__(self):
 6         self._score = None
 7     
 8     def get_score(self):
 9         return self._score
10   
11     def set_score(self, value):
12         self._score = value
13     def del_score(self):
14         del self._score
15     score = property(get_score, set_score, del_score, "I'm the 'score' property")

 

1 a = A()
2 print(a.score) # a.score將觸發getter
3 a.score = 60 #, a.score = 60將觸發setter
4 print(a.score)
5 del a.score #將觸發deleter
6 # print(a.score) #報錯

將 property 函數用作裝飾器可以很方便的創建只讀屬性:

 

1 class Parrot(object):
2     def __init__(self):
3         self._voltage = 100000
4  
5     @property
6     def voltage(self):
7         """Get the current voltage."""
8         return self._voltage

 

注:上面的代碼將 voltage() 方法轉化成同名只讀屬性的 getter 方法。這裏直接不能像上面那個例子,實例化之後修改voltage的值,會報錯。

property 的 getter,setter 和 deleter 方法同樣可以用作裝飾器:

 1 #! /usr/bin/python3
 2 # -*- coding:UTF-8 -*-
 3 
 4 class A(object):
 5     def __init__(self):
 6         self._score = None
 7     
 8     @property
 9     def score(self):
10         return self._score
11     @score.setter
12     def score(self, value):
13         self._score = value
14     @score.deleter
15     def score(self):
16         del self._score

注:這個代碼和第一個例子完全相同,但要注意這些額外函數的名字和 property 下的一樣,例如這裏的 score。


相關鏈接:

1、https://www.runoob.com/python/python-func-property.html

2、https://www.jianshu.com/p/bfbea5f74ab5

 

3、https://www.cnblogs.com/miqi1992/p/8343234.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章