本文主要講述的是對Python中property屬性(特性)的理解,具體如下。
定義及作用:
在property類中,有三個成員方法和三個裝飾器函數。
三個成員方法分別是:fget、fset、fdel,它們分別用來管理屬性訪問;
三個裝飾器函數分別是:getter、setter、deleter,它們分別用來把三個同名的類方法裝飾成property。
fget方法用來管理類實例屬性的獲取,fset方法用來管理類實例屬性的賦值,fdel方法用來管理類實例屬性的刪除;
getter裝飾器把一個自定義類方法裝飾成fget操作,setter裝飾器把一個自定義類方法裝飾成fset操作,deleter裝飾器把一個自定義類方法裝飾成fdel操作。
只要在獲取自定義類實例的屬性時就會自動調用fget成員方法,給自定義類實例的屬性賦值時就會自動調用fset成員方法,在刪除自定義類實例的屬性時就會自動調用fdel成員方法。
下面從三個方面加以說明
Num01–>原始的getter和setter方法,獲取私有屬性值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 定義一個錢的類 class Money( object ): def __init__( self ): self ._money = 0 def getmoney( self ): return self ._money def setmoney( self , value): if isinstance (value, int ): self ._money = value else : print ( "error:不是整型數字" ) money = Money() print (money.getmoney()) # 結果是:0 print ( "====修改錢的大小值====" ) money.setmoney( 100 ) print (money.getmoney()) # 結果是:100 |
Num02–>使用property升級getter和setter方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# 定義一個錢的類 class Money( object ): def __init__( self ): self ._money = 0 def getmoney( self ): return self ._money def setmoney( self , value): if isinstance (value, int ): self ._money = value else : print ( "error:不是整型數字" ) money = property (getmoney, setmoney) money = Money() print (money.getmoney()) # 結果是:0 print ( "====修改錢的大小值====" ) money.setmoney( 100 ) print (money.getmoney()) # 結果是:100 #最后特別需要注意一點:實際錢的值是存在私有便令__money中。而屬性money是一個property對象, 是用來為這個私有變量__money提供接口的。 #如果二者的名字相同,那么就會出現遞歸調用,最終報錯。 |
Num03–>使用property取代getter和setter
@property成為屬性函數,可以對屬性賦值時做必要的檢查,并保證代碼的清晰短小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# 定義一個錢的類 class Money( object ): def __init__( self ): self ._money = 0 @property # 注意使用@property裝飾器對money函數進行裝飾,就會自動生成一個money屬性, 當調用獲取money的值時,就調用該函數 def money( self ): return self ._money @money .setter # 使用生成的money屬性,調用@money.setter裝飾器,設置money的值 def money( self , value): if isinstance (value, int ): self ._money = value else : print ( "error:不是整型數字" ) aa = Money() print (aa.money) # 結果是:0 print ( "====修改錢的大小值====" ) aa.money = 100 print (aa.money) # 結果是:100 |
總結
以上就是本文關于Python中property屬性實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/u014745194/article/details/70432673